Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(iot) Feature/issue 1038 iot core (#1359)

nblomquist326b49549637
diff --git a/.gitattributes b/.gitattributes
index 89a570804c..9149db5d64 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -19,6 +19,7 @@ mvnw.cmd text eol=crlf
*.fla binary
*.swf binary
*.gz binary
+*.jar binary
*.zip binary
*.7z binary
*.ttf binary
diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml
index c859503735..7275848d84 100644
--- a/.github/workflows/compatibility.yml
+++ b/.github/workflows/compatibility.yml
@@ -106,6 +106,7 @@ jobs:
-e FLOCI_BASE_URL=http://floci:4566 \
-e FLOCI_SERVICES_DOCKER_NETWORK=compat-net \
-e FLOCI_HOSTNAME=floci \
+ -e FLOCI_SERVICES_IOT_MQTT_ENABLED=true \
-e FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true \
-e FLOCI_TLS_ENABLED=true \
-e FLOCI_SERVICES_EC2_MOCK=true \
diff --git a/.gitignore b/.gitignore
index fc7348525f..7a859fd4b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@ target/
data/
*.class
*.jar
+!vendor/maven/**/*.jar
*.war
.idea/
*.iml
diff --git a/AGENTS.md b/AGENTS.md
index f90f755fa4..8a0f68e1ad 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -269,6 +269,7 @@ When adding functionality:
- Prefer self-explanatory code over comments
- Avoid unnecessary comments
- Always use braces in conditionals
+- Never leave a `catch` block empty. If an exception is intentionally tolerated, log it with enough context to diagnose it later.
- Follow existing project patterns
- Use modern Java features only when they improve clarity
diff --git a/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go b/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go
index 9d1a8fbb22..5af24a509e 100644
--- a/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go
+++ b/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go
@@ -11,21 +11,24 @@ import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/acm"
- "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
- "github.com/aws/aws-sdk-go-v2/service/ecr"
- "github.com/aws/aws-sdk-go-v2/service/pipes"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
+ "github.com/aws/aws-sdk-go-v2/service/ecr"
"github.com/aws/aws-sdk-go-v2/service/glue"
"github.com/aws/aws-sdk-go-v2/service/iam"
+ "github.com/aws/aws-sdk-go-v2/service/iot"
+ "github.com/aws/aws-sdk-go-v2/service/iotdataplane"
+ "github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane"
"github.com/aws/aws-sdk-go-v2/service/kinesis"
"github.com/aws/aws-sdk-go-v2/service/kms"
"github.com/aws/aws-sdk-go-v2/service/lambda"
"github.com/aws/aws-sdk-go-v2/service/neptune"
+ "github.com/aws/aws-sdk-go-v2/service/pipes"
"github.com/aws/aws-sdk-go-v2/service/rds"
+ "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
- "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/ssm"
@@ -141,6 +144,21 @@ func PipesClient() *pipes.Client {
return pipes.NewFromConfig(Config())
}
+// IoTClient returns a new AWS IoT client.
+func IoTClient() *iot.Client {
+ return iot.NewFromConfig(Config())
+}
+
+// IoTDataClient returns a new AWS IoT Data Plane client.
+func IoTDataClient() *iotdataplane.Client {
+ return iotdataplane.NewFromConfig(Config())
+}
+
+// IoTJobsDataClient returns a new AWS IoT Jobs Data Plane client.
+func IoTJobsDataClient() *iotjobsdataplane.Client {
+ return iotjobsdataplane.NewFromConfig(Config())
+}
+
// RDSClient returns a new RDS client.
func RDSClient() *rds.Client {
return rds.NewFromConfig(Config())
diff --git a/compatibility-tests/sdk-test-go/tests/iot_test.go b/compatibility-tests/sdk-test-go/tests/iot_test.go
new file mode 100644
index 0000000000..348fd183d4
--- /dev/null
+++ b/compatibility-tests/sdk-test-go/tests/iot_test.go
@@ -0,0 +1,733 @@
+package tests
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net"
+ "strings"
+ "testing"
+ "time"
+
+ "floci-sdk-test-go/internal/testutil"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/dynamodb"
+ ddbtypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
+ "github.com/aws/aws-sdk-go-v2/service/iot"
+ iottypes "github.com/aws/aws-sdk-go-v2/service/iot/types"
+ "github.com/aws/aws-sdk-go-v2/service/iotdataplane"
+ jobsdata "github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane"
+ jobsdatatypes "github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane/types"
+ "github.com/aws/aws-sdk-go-v2/service/kinesis"
+ kinesistypes "github.com/aws/aws-sdk-go-v2/service/kinesis/types"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/sqs"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestIoT(t *testing.T) {
+ ctx := context.Background()
+ svc := testutil.IoTClient()
+
+ t.Run("DescribeEndpoint", func(t *testing.T) {
+ response, err := svc.DescribeEndpoint(ctx, &iot.DescribeEndpointInput{
+ EndpointType: aws.String("iot:Data-ATS"),
+ })
+ require.NoError(t, err)
+ assert.NotEmpty(t, aws.ToString(response.EndpointAddress))
+ })
+
+ t.Run("ThingRegistryCrud", func(t *testing.T) {
+ thingName := "go-iot-thing"
+ otherThingName := "go-iot-other-thing"
+ _, _ = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+ _, _ = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(otherThingName)})
+
+ _, err := svc.DescribeThing(ctx, &iot.DescribeThingInput{ThingName: aws.String(thingName)})
+ require.Error(t, err)
+
+ created, err := svc.CreateThing(ctx, &iot.CreateThingInput{
+ ThingName: aws.String(thingName),
+ AttributePayload: &iottypes.AttributePayload{
+ Attributes: map[string]string{"env": "go"},
+ },
+ })
+ require.NoError(t, err)
+ assert.Equal(t, thingName, aws.ToString(created.ThingName))
+ assert.True(t, strings.HasSuffix(aws.ToString(created.ThingArn), ":thing/"+thingName))
+
+ idempotent, err := svc.CreateThing(ctx, &iot.CreateThingInput{
+ ThingName: aws.String(thingName),
+ AttributePayload: &iottypes.AttributePayload{
+ Attributes: map[string]string{"env": "go"},
+ },
+ })
+ require.NoError(t, err)
+ assert.Equal(t, thingName, aws.ToString(idempotent.ThingName))
+
+ _, err = svc.CreateThing(ctx, &iot.CreateThingInput{ThingName: aws.String(thingName)})
+ require.Error(t, err)
+
+ described, err := svc.DescribeThing(ctx, &iot.DescribeThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ assert.Equal(t, "go", described.Attributes["env"])
+ _, err = svc.CreateThing(ctx, &iot.CreateThingInput{ThingName: aws.String(otherThingName)})
+ require.NoError(t, err)
+
+ listed, err := svc.ListThings(ctx, &iot.ListThingsInput{})
+ require.NoError(t, err)
+ found := false
+ for _, thing := range listed.Things {
+ if aws.ToString(thing.ThingName) == thingName {
+ found = true
+ }
+ }
+ assert.True(t, found)
+
+ firstPage, err := svc.ListThings(ctx, &iot.ListThingsInput{MaxResults: aws.Int32(1)})
+ require.NoError(t, err)
+ require.Len(t, firstPage.Things, 1)
+ require.NotEmpty(t, aws.ToString(firstPage.NextToken))
+ secondPage, err := svc.ListThings(ctx, &iot.ListThingsInput{MaxResults: aws.Int32(1), NextToken: firstPage.NextToken})
+ require.NoError(t, err)
+ require.Len(t, secondPage.Things, 1)
+
+ _, err = svc.UpdateThing(ctx, &iot.UpdateThingInput{
+ ThingName: aws.String(thingName),
+ AttributePayload: &iottypes.AttributePayload{
+ Attributes: map[string]string{"env": "updated", "owner": "iot"},
+ },
+ })
+ require.NoError(t, err)
+ _, err = svc.UpdateThing(ctx, &iot.UpdateThingInput{
+ ThingName: aws.String(thingName),
+ ExpectedVersion: aws.Int64(2),
+ AttributePayload: &iottypes.AttributePayload{Attributes: map[string]string{"env": "versioned", "owner": "iot"}},
+ })
+ require.NoError(t, err)
+ _, err = svc.UpdateThing(ctx, &iot.UpdateThingInput{
+ ThingName: aws.String(thingName),
+ ExpectedVersion: aws.Int64(2),
+ AttributePayload: &iottypes.AttributePayload{Attributes: map[string]string{"env": "stale"}},
+ })
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "VersionConflictException")
+
+ updated, err := svc.DescribeThing(ctx, &iot.DescribeThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ assert.Equal(t, "versioned", updated.Attributes["env"])
+ assert.Equal(t, "iot", updated.Attributes["owner"])
+
+ _, err = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ _, err = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(otherThingName)})
+ require.NoError(t, err)
+
+ _, err = svc.DescribeThing(ctx, &iot.DescribeThingInput{ThingName: aws.String(thingName)})
+ require.Error(t, err)
+ })
+
+ t.Run("ThingTags", func(t *testing.T) {
+ thingName := "go-iot-tagged-thing"
+ _, _ = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+
+ created, err := svc.CreateThing(ctx, &iot.CreateThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ thingArn := aws.ToString(created.ThingArn)
+
+ listed, err := svc.ListTagsForResource(ctx, &iot.ListTagsForResourceInput{ResourceArn: aws.String(thingArn)})
+ require.NoError(t, err)
+ assert.Empty(t, listed.Tags)
+
+ _, err = svc.TagResource(ctx, &iot.TagResourceInput{
+ ResourceArn: aws.String(thingArn),
+ Tags: []iottypes.Tag{
+ {Key: aws.String("env"), Value: aws.String("go")},
+ {Key: aws.String("owner"), Value: aws.String("iot")},
+ },
+ })
+ require.NoError(t, err)
+
+ listed, err = svc.ListTagsForResource(ctx, &iot.ListTagsForResourceInput{ResourceArn: aws.String(thingArn)})
+ require.NoError(t, err)
+ assert.Equal(t, map[string]string{"env": "go", "owner": "iot"}, tagsByKey(listed.Tags))
+
+ _, err = svc.UntagResource(ctx, &iot.UntagResourceInput{
+ ResourceArn: aws.String(thingArn),
+ TagKeys: []string{"env"},
+ })
+ require.NoError(t, err)
+
+ listed, err = svc.ListTagsForResource(ctx, &iot.ListTagsForResourceInput{ResourceArn: aws.String(thingArn)})
+ require.NoError(t, err)
+ assert.Equal(t, map[string]string{"owner": "iot"}, tagsByKey(listed.Tags))
+
+ _, err = svc.ListTagsForResource(ctx, &iot.ListTagsForResourceInput{
+ ResourceArn: aws.String("arn:aws:iot:us-east-1:000000000000:thing/missing-tagged-thing"),
+ })
+ require.Error(t, err)
+ })
+
+ t.Run("CertificatesPoliciesAndAttachments", func(t *testing.T) {
+ createdCert, err := svc.CreateKeysAndCertificate(ctx, &iot.CreateKeysAndCertificateInput{SetAsActive: true})
+ require.NoError(t, err)
+ certArn := aws.ToString(createdCert.CertificateArn)
+ certID := aws.ToString(createdCert.CertificateId)
+ assert.Contains(t, aws.ToString(createdCert.CertificatePem), "BEGIN CERTIFICATE")
+ require.NotNil(t, createdCert.KeyPair)
+
+ described, err := svc.DescribeCertificate(ctx, &iot.DescribeCertificateInput{CertificateId: aws.String(certID)})
+ require.NoError(t, err)
+ assert.Equal(t, iottypes.CertificateStatusActive, described.CertificateDescription.Status)
+
+ listedCerts, err := svc.ListCertificates(ctx, &iot.ListCertificatesInput{})
+ require.NoError(t, err)
+ assert.NotEmpty(t, listedCerts.Certificates)
+
+ _, err = svc.UpdateCertificate(ctx, &iot.UpdateCertificateInput{CertificateId: aws.String(certID), NewStatus: iottypes.CertificateStatusInactive})
+ require.NoError(t, err)
+
+ described, err = svc.DescribeCertificate(ctx, &iot.DescribeCertificateInput{CertificateId: aws.String(certID)})
+ require.NoError(t, err)
+ assert.Equal(t, iottypes.CertificateStatusInactive, described.CertificateDescription.Status)
+
+ policyName := "go-iot-policy"
+ policyDocument := `{"Version":"2012-10-17","Statement":[]}`
+ createdPolicy, err := svc.CreatePolicy(ctx, &iot.CreatePolicyInput{PolicyName: aws.String(policyName), PolicyDocument: aws.String(policyDocument)})
+ require.NoError(t, err)
+ assert.Equal(t, policyName, aws.ToString(createdPolicy.PolicyName))
+
+ gotPolicy, err := svc.GetPolicy(ctx, &iot.GetPolicyInput{PolicyName: aws.String(policyName)})
+ require.NoError(t, err)
+ assert.Contains(t, aws.ToString(gotPolicy.PolicyDocument), "2012-10-17")
+
+ listedPolicies, err := svc.ListPolicies(ctx, &iot.ListPoliciesInput{})
+ require.NoError(t, err)
+ assert.NotEmpty(t, listedPolicies.Policies)
+
+ _, err = svc.AttachPolicy(ctx, &iot.AttachPolicyInput{PolicyName: aws.String(policyName), Target: aws.String(certArn)})
+ require.NoError(t, err)
+ _, err = svc.DetachPolicy(ctx, &iot.DetachPolicyInput{PolicyName: aws.String(policyName), Target: aws.String(certArn)})
+ require.NoError(t, err)
+
+ thingName := "go-iot-principal-thing"
+ _, _ = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+ _, err = svc.CreateThing(ctx, &iot.CreateThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ _, err = svc.AttachThingPrincipal(ctx, &iot.AttachThingPrincipalInput{ThingName: aws.String(thingName), Principal: aws.String(certArn)})
+ require.NoError(t, err)
+ principals, err := svc.ListThingPrincipals(ctx, &iot.ListThingPrincipalsInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ assert.Contains(t, principals.Principals, certArn)
+ _, err = svc.DetachThingPrincipal(ctx, &iot.DetachThingPrincipalInput{ThingName: aws.String(thingName), Principal: aws.String(certArn)})
+ require.NoError(t, err)
+ })
+
+ t.Run("IoTDataShadowsAndPublish", func(t *testing.T) {
+ dataSvc := testutil.IoTDataClient()
+ thingName := "go-iot-shadow-thing"
+
+ _, err := dataSvc.DeleteConnection(ctx, &iotdataplane.DeleteConnectionInput{ClientId: aws.String("go-iot-missing-client")})
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "ResourceNotFoundException")
+
+ _, err = dataSvc.GetThingShadow(ctx, &iotdataplane.GetThingShadowInput{ThingName: aws.String(thingName)})
+ require.Error(t, err)
+
+ updated, err := dataSvc.UpdateThingShadow(ctx, &iotdataplane.UpdateThingShadowInput{
+ ThingName: aws.String(thingName),
+ Payload: []byte(`{"state":{"desired":{"color":"blue"}}}`),
+ })
+ require.NoError(t, err)
+ var shadow map[string]any
+ require.NoError(t, json.Unmarshal(updated.Payload, &shadow))
+ assert.Equal(t, float64(1), shadow["version"])
+
+ _, err = dataSvc.UpdateThingShadow(ctx, &iotdataplane.UpdateThingShadowInput{
+ ThingName: aws.String(thingName),
+ Payload: []byte(`{"state":{"reported":{"color":"green"}}}`),
+ })
+ require.NoError(t, err)
+
+ got, err := dataSvc.GetThingShadow(ctx, &iotdataplane.GetThingShadowInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal(got.Payload, &shadow))
+ state := shadow["state"].(map[string]any)
+ assert.Equal(t, "blue", state["desired"].(map[string]any)["color"])
+ assert.Equal(t, "green", state["reported"].(map[string]any)["color"])
+
+ _, err = dataSvc.UpdateThingShadow(ctx, &iotdataplane.UpdateThingShadowInput{
+ ThingName: aws.String(thingName),
+ ShadowName: aws.String("settings"),
+ Payload: []byte(`{"state":{"desired":{"mode":"auto"}}}`),
+ })
+ require.NoError(t, err)
+ named, err := dataSvc.ListNamedShadowsForThing(ctx, &iotdataplane.ListNamedShadowsForThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ assert.Contains(t, named.Results, "settings")
+
+ _, err = dataSvc.Publish(ctx, &iotdataplane.PublishInput{Topic: aws.String("devices/" + thingName + "/events"), Payload: []byte("payload")})
+ require.NoError(t, err)
+ _, err = dataSvc.DeleteThingShadow(ctx, &iotdataplane.DeleteThingShadowInput{ThingName: aws.String(thingName), ShadowName: aws.String("settings")})
+ require.NoError(t, err)
+ _, err = dataSvc.DeleteThingShadow(ctx, &iotdataplane.DeleteThingShadowInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ })
+
+ t.Run("TopicRuleCrudAndRuleActions", func(t *testing.T) {
+ dataSvc := testutil.IoTDataClient()
+ dynamoSvc := testutil.DynamoDBClient()
+ kinesisSvc := testutil.KinesisClient()
+ s3Svc := testutil.S3Client()
+ sqsSvc := testutil.SQSClient()
+ ruleName := "go-iot-topic-rule"
+ bucketName := "go-iot-rule-bucket"
+ dynamoTable := "go-iot-rule-table"
+ streamName := "go-iot-rule-stream"
+ objectKey := "rules/output.json"
+ queueName := "go-iot-rule-queue"
+ _, _ = dynamoSvc.DeleteTable(ctx, &dynamodb.DeleteTableInput{TableName: aws.String(dynamoTable)})
+ _, _ = kinesisSvc.DeleteStream(ctx, &kinesis.DeleteStreamInput{StreamName: aws.String(streamName)})
+ _, _ = s3Svc.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)})
+ _, _ = s3Svc.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucketName)})
+ _, err := dynamoSvc.CreateTable(ctx, &dynamodb.CreateTableInput{
+ TableName: aws.String(dynamoTable),
+ BillingMode: ddbtypes.BillingModePayPerRequest,
+ AttributeDefinitions: []ddbtypes.AttributeDefinition{
+ {AttributeName: aws.String("pk"), AttributeType: ddbtypes.ScalarAttributeTypeS},
+ {AttributeName: aws.String("sk"), AttributeType: ddbtypes.ScalarAttributeTypeS},
+ },
+ KeySchema: []ddbtypes.KeySchemaElement{
+ {AttributeName: aws.String("pk"), KeyType: ddbtypes.KeyTypeHash},
+ {AttributeName: aws.String("sk"), KeyType: ddbtypes.KeyTypeRange},
+ },
+ })
+ require.NoError(t, err)
+ defer dynamoSvc.DeleteTable(ctx, &dynamodb.DeleteTableInput{TableName: aws.String(dynamoTable)})
+ _, err = kinesisSvc.CreateStream(ctx, &kinesis.CreateStreamInput{StreamName: aws.String(streamName), ShardCount: aws.Int32(1)})
+ require.NoError(t, err)
+ defer kinesisSvc.DeleteStream(ctx, &kinesis.DeleteStreamInput{StreamName: aws.String(streamName)})
+ _, err = s3Svc.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucketName)})
+ require.NoError(t, err)
+ defer s3Svc.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)})
+ defer s3Svc.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucketName)})
+ queue, err := sqsSvc.CreateQueue(ctx, &sqs.CreateQueueInput{QueueName: aws.String(queueName)})
+ require.NoError(t, err)
+ queueURL := aws.ToString(queue.QueueUrl)
+ defer sqsSvc.DeleteQueue(ctx, &sqs.DeleteQueueInput{QueueUrl: aws.String(queueURL)})
+ defer svc.DeleteTopicRule(ctx, &iot.DeleteTopicRuleInput{RuleName: aws.String(ruleName)})
+ payload := []byte(`{"pk":"iot#1","sk":"event","message":"go-rule-payload"}`)
+
+ _, err = svc.CreateTopicRule(ctx, &iot.CreateTopicRuleInput{
+ RuleName: aws.String(ruleName),
+ TopicRulePayload: &iottypes.TopicRulePayload{
+ Sql: aws.String("SELECT * FROM 'devices/go-iot/rules'"),
+ Description: aws.String("go topic rule"),
+ RuleDisabled: aws.Bool(false),
+ Actions: []iottypes.Action{
+ {Sqs: &iottypes.SqsAction{
+ RoleArn: aws.String("arn:aws:iam::000000000000:role/iot-rule-role"),
+ QueueUrl: aws.String(queueURL),
+ UseBase64: aws.Bool(false),
+ }},
+ {S3: &iottypes.S3Action{
+ RoleArn: aws.String("arn:aws:iam::000000000000:role/iot-rule-role"),
+ BucketName: aws.String(bucketName),
+ Key: aws.String(objectKey),
+ }},
+ {Kinesis: &iottypes.KinesisAction{
+ RoleArn: aws.String("arn:aws:iam::000000000000:role/iot-rule-role"),
+ StreamName: aws.String(streamName),
+ PartitionKey: aws.String("iot-rule"),
+ }},
+ {DynamoDBv2: &iottypes.DynamoDBv2Action{
+ RoleArn: aws.String("arn:aws:iam::000000000000:role/iot-rule-role"),
+ PutItem: &iottypes.PutItemInput{TableName: aws.String(dynamoTable)},
+ }},
+ },
+ },
+ })
+ require.NoError(t, err)
+
+ got, err := svc.GetTopicRule(ctx, &iot.GetTopicRuleInput{RuleName: aws.String(ruleName)})
+ require.NoError(t, err)
+ require.NotNil(t, got.Rule)
+ assert.Equal(t, ruleName, aws.ToString(got.Rule.RuleName))
+ assert.Equal(t, queueURL, aws.ToString(got.Rule.Actions[0].Sqs.QueueUrl))
+ assert.Equal(t, bucketName, aws.ToString(got.Rule.Actions[1].S3.BucketName))
+ assert.Equal(t, streamName, aws.ToString(got.Rule.Actions[2].Kinesis.StreamName))
+ assert.Equal(t, dynamoTable, aws.ToString(got.Rule.Actions[3].DynamoDBv2.PutItem.TableName))
+
+ _, err = svc.DisableTopicRule(ctx, &iot.DisableTopicRuleInput{RuleName: aws.String(ruleName)})
+ require.NoError(t, err)
+ listed, err := svc.ListTopicRules(ctx, &iot.ListTopicRulesInput{})
+ require.NoError(t, err)
+ foundDisabled := false
+ for _, rule := range listed.Rules {
+ if aws.ToString(rule.RuleName) == ruleName && aws.ToBool(rule.RuleDisabled) {
+ foundDisabled = true
+ }
+ }
+ assert.True(t, foundDisabled)
+
+ _, err = svc.EnableTopicRule(ctx, &iot.EnableTopicRuleInput{RuleName: aws.String(ruleName)})
+ require.NoError(t, err)
+ _, err = dataSvc.Publish(ctx, &iotdataplane.PublishInput{Topic: aws.String("devices/go-iot/rules"), Payload: payload})
+ require.NoError(t, err)
+
+ received, err := sqsSvc.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{QueueUrl: aws.String(queueURL), MaxNumberOfMessages: 1})
+ require.NoError(t, err)
+ require.Len(t, received.Messages, 1)
+ assert.Equal(t, string(payload), aws.ToString(received.Messages[0].Body))
+
+ object, err := s3Svc.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)})
+ require.NoError(t, err)
+ defer object.Body.Close()
+ body, err := io.ReadAll(object.Body)
+ require.NoError(t, err)
+ assert.Equal(t, string(payload), string(body))
+
+ dynamoItem, err := dynamoSvc.GetItem(ctx, &dynamodb.GetItemInput{
+ TableName: aws.String(dynamoTable),
+ Key: map[string]ddbtypes.AttributeValue{
+ "pk": &ddbtypes.AttributeValueMemberS{Value: "iot#1"},
+ "sk": &ddbtypes.AttributeValueMemberS{Value: "event"},
+ },
+ })
+ require.NoError(t, err)
+ message, ok := dynamoItem.Item["message"].(*ddbtypes.AttributeValueMemberS)
+ require.True(t, ok)
+ assert.Equal(t, "go-rule-payload", message.Value)
+
+ stream, err := kinesisSvc.DescribeStream(ctx, &kinesis.DescribeStreamInput{StreamName: aws.String(streamName)})
+ require.NoError(t, err)
+ iterator, err := kinesisSvc.GetShardIterator(ctx, &kinesis.GetShardIteratorInput{
+ StreamName: aws.String(streamName),
+ ShardId: stream.StreamDescription.Shards[0].ShardId,
+ ShardIteratorType: kinesistypes.ShardIteratorTypeTrimHorizon,
+ })
+ require.NoError(t, err)
+ records, err := kinesisSvc.GetRecords(ctx, &kinesis.GetRecordsInput{ShardIterator: iterator.ShardIterator})
+ require.NoError(t, err)
+ require.NotEmpty(t, records.Records)
+ assert.Equal(t, payload, records.Records[0].Data)
+ })
+
+ t.Run("ThingTypesGroupsAndJobs", func(t *testing.T) {
+ jobsSvc := testutil.IoTJobsDataClient()
+ thingType := "go-iot-type"
+ thingName := "go-iot-typed-thing"
+ groupName := "go-iot-group"
+ jobID := "go-iot-job"
+ _, _ = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+ _, _ = svc.DeleteThingGroup(ctx, &iot.DeleteThingGroupInput{ThingGroupName: aws.String(groupName)})
+ _, _ = svc.DeprecateThingType(ctx, &iot.DeprecateThingTypeInput{ThingTypeName: aws.String(thingType)})
+ _, _ = svc.DeleteThingType(ctx, &iot.DeleteThingTypeInput{ThingTypeName: aws.String(thingType)})
+
+ jobsEndpoint, err := svc.DescribeEndpoint(ctx, &iot.DescribeEndpointInput{EndpointType: aws.String("iot:Jobs")})
+ require.NoError(t, err)
+ assert.NotEmpty(t, aws.ToString(jobsEndpoint.EndpointAddress))
+
+ createdType, err := svc.CreateThingType(ctx, &iot.CreateThingTypeInput{
+ ThingTypeName: aws.String(thingType),
+ ThingTypeProperties: &iottypes.ThingTypeProperties{
+ ThingTypeDescription: aws.String("go type"),
+ SearchableAttributes: []string{"model"},
+ },
+ })
+ require.NoError(t, err)
+ assert.Equal(t, thingType, aws.ToString(createdType.ThingTypeName))
+ describedType, err := svc.DescribeThingType(ctx, &iot.DescribeThingTypeInput{ThingTypeName: aws.String(thingType)})
+ require.NoError(t, err)
+ assert.Equal(t, "go type", aws.ToString(describedType.ThingTypeProperties.ThingTypeDescription))
+
+ _, err = svc.UpdateThingType(ctx, &iot.UpdateThingTypeInput{
+ ThingTypeName: aws.String(thingType),
+ ThingTypeProperties: &iottypes.ThingTypeProperties{
+ ThingTypeDescription: aws.String("go type updated"),
+ SearchableAttributes: []string{"model", "fw"},
+ },
+ })
+ require.NoError(t, err)
+
+ createdThing, err := svc.CreateThing(ctx, &iot.CreateThingInput{
+ ThingName: aws.String(thingName),
+ ThingTypeName: aws.String(thingType),
+ AttributePayload: &iottypes.AttributePayload{
+ Attributes: map[string]string{"model": "g1"},
+ },
+ })
+ require.NoError(t, err)
+ thingArn := aws.ToString(createdThing.ThingArn)
+ describedThing, err := svc.DescribeThing(ctx, &iot.DescribeThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ assert.Equal(t, thingType, aws.ToString(describedThing.ThingTypeName))
+
+ createdGroup, err := svc.CreateThingGroup(ctx, &iot.CreateThingGroupInput{
+ ThingGroupName: aws.String(groupName),
+ ThingGroupProperties: &iottypes.ThingGroupProperties{
+ ThingGroupDescription: aws.String("go group"),
+ AttributePayload: &iottypes.AttributePayload{Attributes: map[string]string{"fleet": "go"}},
+ },
+ })
+ require.NoError(t, err)
+ assert.Equal(t, groupName, aws.ToString(createdGroup.ThingGroupName))
+ _, err = svc.AddThingToThingGroup(ctx, &iot.AddThingToThingGroupInput{ThingGroupName: aws.String(groupName), ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ thingsInGroup, err := svc.ListThingsInThingGroup(ctx, &iot.ListThingsInThingGroupInput{ThingGroupName: aws.String(groupName)})
+ require.NoError(t, err)
+ assert.Contains(t, thingsInGroup.Things, thingName)
+
+ jobDoc := `{"operation":"reboot"}`
+ createdJob, err := svc.CreateJob(ctx, &iot.CreateJobInput{JobId: aws.String(jobID), Targets: []string{thingArn}, Document: aws.String(jobDoc), Description: aws.String("go job")})
+ require.NoError(t, err)
+ assert.Equal(t, jobID, aws.ToString(createdJob.JobId))
+ pending, err := jobsSvc.GetPendingJobExecutions(ctx, &jobsdata.GetPendingJobExecutionsInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ require.NotEmpty(t, pending.QueuedJobs)
+ started, err := jobsSvc.StartNextPendingJobExecution(ctx, &jobsdata.StartNextPendingJobExecutionInput{ThingName: aws.String(thingName), StatusDetails: map[string]string{"phase": "download"}})
+ require.NoError(t, err)
+ assert.Equal(t, jobsdatatypes.JobExecutionStatusInProgress, started.Execution.Status)
+ updated, err := jobsSvc.UpdateJobExecution(ctx, &jobsdata.UpdateJobExecutionInput{
+ ThingName: aws.String(thingName),
+ JobId: aws.String(jobID),
+ Status: jobsdatatypes.JobExecutionStatusSucceeded,
+ ExpectedVersion: aws.Int64(2),
+ IncludeJobExecutionState: aws.Bool(true),
+ IncludeJobDocument: aws.Bool(true),
+ })
+ require.NoError(t, err)
+ assert.Equal(t, jobsdatatypes.JobExecutionStatusSucceeded, updated.ExecutionState.Status)
+ assert.Contains(t, aws.ToString(updated.JobDocument), "reboot")
+
+ _, err = svc.RemoveThingFromThingGroup(ctx, &iot.RemoveThingFromThingGroupInput{ThingGroupName: aws.String(groupName), ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ _, err = svc.DeleteThingGroup(ctx, &iot.DeleteThingGroupInput{ThingGroupName: aws.String(groupName)})
+ require.NoError(t, err)
+ _, err = svc.DeleteThing(ctx, &iot.DeleteThingInput{ThingName: aws.String(thingName)})
+ require.NoError(t, err)
+ _, err = svc.DeprecateThingType(ctx, &iot.DeprecateThingTypeInput{ThingTypeName: aws.String(thingType)})
+ require.NoError(t, err)
+ _, err = svc.DeleteThingType(ctx, &iot.DeleteThingTypeInput{ThingTypeName: aws.String(thingType)})
+ require.NoError(t, err)
+ })
+
+ t.Run("MqttConnectPublishSubscribe", func(t *testing.T) {
+ topic := "devices/go-iot-mqtt/events"
+ payload := []byte("go-mqtt")
+
+ subscriber := mqttConnect(t, "go-iot-mqtt-sub")
+ defer subscriber.Close()
+ mqttSubscribe(t, subscriber, topic)
+
+ publisher := mqttConnect(t, "go-iot-mqtt-pub")
+ mqttPublish(t, publisher, topic, payload)
+ publisher.Close()
+
+ receivedTopic, receivedPayload := mqttReadPublish(t, subscriber)
+ assert.Equal(t, topic, receivedTopic)
+ assert.Equal(t, payload, receivedPayload)
+ })
+
+ t.Run("IoTDataConnectionApis", func(t *testing.T) {
+ dataSvc := testutil.IoTDataClient()
+ clientID := "go-iot-connection"
+ topic := "devices/go-iot-connection/direct"
+ payload := []byte("go-direct")
+
+ client := mqttConnect(t, clientID)
+ defer client.Close()
+ mqttSubscribe(t, client, topic)
+
+ connection, err := dataSvc.GetConnection(ctx, &iotdataplane.GetConnectionInput{
+ ClientId: aws.String(clientID),
+ IncludeSocketInformation: true,
+ })
+ require.NoError(t, err)
+ assert.Equal(t, clientID, aws.ToString(connection.ClientId))
+ assert.True(t, connection.Connected)
+ assert.NotEmpty(t, aws.ToString(connection.SourceIp))
+
+ subscriptions, err := dataSvc.ListSubscriptions(ctx, &iotdataplane.ListSubscriptionsInput{ClientId: aws.String(clientID)})
+ require.NoError(t, err)
+ require.NotEmpty(t, subscriptions.Subscriptions)
+ assert.Equal(t, topic, aws.ToString(subscriptions.Subscriptions[0].TopicFilter))
+
+ direct, err := dataSvc.SendDirectMessage(ctx, &iotdataplane.SendDirectMessageInput{
+ ClientId: aws.String(clientID),
+ Topic: aws.String(topic),
+ Payload: payload,
+ })
+ require.NoError(t, err)
+ assert.NotEmpty(t, aws.ToString(direct.TraceId))
+
+ receivedTopic, receivedPayload := mqttReadPublish(t, client)
+ assert.Equal(t, topic, receivedTopic)
+ assert.Equal(t, payload, receivedPayload)
+ })
+
+ t.Run("Mqtt5Connect", func(t *testing.T) {
+ client := mqtt5Connect(t, "go-iot-mqtt5")
+ client.Close()
+ })
+
+ t.Run("MqttShadowReservedTopics", func(t *testing.T) {
+ thingName := "go-iot-shadow"
+ subscriber := mqttConnect(t, "go-iot-shadow-sub")
+ defer subscriber.Close()
+ mqttSubscribe(t, subscriber, "$aws/things/"+thingName+"/shadow/update/accepted")
+ mqttSubscribe(t, subscriber, "$aws/things/"+thingName+"/shadow/get/accepted")
+ mqttSubscribe(t, subscriber, "$aws/things/"+thingName+"/shadow/delete/accepted")
+
+ publisher := mqttConnect(t, "go-iot-shadow-pub")
+ defer publisher.Close()
+ mqttPublish(t, publisher, "$aws/things/"+thingName+"/shadow/update", []byte(`{"state":{"desired":{"color":"blue"}},"clientToken":"update-token"}`))
+ topic, payload := mqttReadPublish(t, subscriber)
+ assert.Equal(t, "$aws/things/"+thingName+"/shadow/update/accepted", topic)
+ var accepted map[string]any
+ require.NoError(t, json.Unmarshal(payload, &accepted))
+ assert.Equal(t, "update-token", accepted["clientToken"])
+
+ mqttPublish(t, publisher, "$aws/things/"+thingName+"/shadow/get", []byte(`{"clientToken":"get-token"}`))
+ topic, payload = mqttReadPublish(t, subscriber)
+ assert.Equal(t, "$aws/things/"+thingName+"/shadow/get/accepted", topic)
+ var got map[string]any
+ require.NoError(t, json.Unmarshal(payload, &got))
+ assert.Equal(t, "get-token", got["clientToken"])
+
+ mqttPublish(t, publisher, "$aws/things/"+thingName+"/shadow/delete", []byte(`{"clientToken":"delete-token"}`))
+ topic, payload = mqttReadPublish(t, subscriber)
+ assert.Equal(t, "$aws/things/"+thingName+"/shadow/delete/accepted", topic)
+ var deleted map[string]any
+ require.NoError(t, json.Unmarshal(payload, &deleted))
+ assert.Equal(t, "delete-token", deleted["clientToken"])
+ })
+}
+
+func tagsByKey(tags []iottypes.Tag) map[string]string {
+ result := map[string]string{}
+ for _, tag := range tags {
+ result[aws.ToString(tag.Key)] = aws.ToString(tag.Value)
+ }
+ return result
+}
+
+func mqttConnect(t *testing.T, clientID string) net.Conn {
+ t.Helper()
+ conn, err := net.DialTimeout("tcp", "floci:1883", 5*time.Second)
+ require.NoError(t, err)
+ require.NoError(t, conn.SetDeadline(time.Now().Add(5*time.Second)))
+ body := append(mqttUTF8("MQTT"), []byte{4, 2, 0, 60}...)
+ body = append(body, mqttUTF8(clientID)...)
+ _, err = conn.Write(append([]byte{0x10}, append(mqttRemainingLength(len(body)), body...)...))
+ require.NoError(t, err)
+ packet := mqttReadPacket(t, conn)
+ require.Equal(t, []byte{0x20, 0x02, 0x00, 0x00}, packet)
+ return conn
+}
+
+func mqtt5Connect(t *testing.T, clientID string) net.Conn {
+ t.Helper()
+ conn, err := net.DialTimeout("tcp", "floci:1883", 5*time.Second)
+ require.NoError(t, err)
+ require.NoError(t, conn.SetDeadline(time.Now().Add(5*time.Second)))
+ body := append(mqttUTF8("MQTT"), []byte{5, 2, 0, 60, 0}...)
+ body = append(body, mqttUTF8(clientID)...)
+ _, err = conn.Write(append([]byte{0x10}, append(mqttRemainingLength(len(body)), body...)...))
+ require.NoError(t, err)
+ packet := mqttReadPacket(t, conn)
+ mqttAssertV5Connack(t, packet)
+ return conn
+}
+
+func mqttAssertV5Connack(t *testing.T, packet []byte) {
+ t.Helper()
+ require.Equal(t, byte(0x20), packet[0])
+ index := 1
+ for packet[index]&0x80 != 0 {
+ index++
+ }
+ index++
+ require.Equal(t, byte(0x00), packet[index])
+ require.Equal(t, byte(0x00), packet[index+1])
+}
+
+func mqttSubscribe(t *testing.T, conn net.Conn, topic string) {
+ t.Helper()
+ body := append([]byte{0, 1}, mqttUTF8(topic)...)
+ body = append(body, 0)
+ _, err := conn.Write(append([]byte{0x82}, append(mqttRemainingLength(len(body)), body...)...))
+ require.NoError(t, err)
+ require.Equal(t, []byte{0x90, 0x03, 0x00, 0x01, 0x00}, mqttReadPacket(t, conn))
+}
+
+func mqttPublish(t *testing.T, conn net.Conn, topic string, payload []byte) {
+ t.Helper()
+ body := append(mqttUTF8(topic), payload...)
+ _, err := conn.Write(append([]byte{0x30}, append(mqttRemainingLength(len(body)), body...)...))
+ require.NoError(t, err)
+}
+
+func mqttReadPublish(t *testing.T, conn net.Conn) (string, []byte) {
+ t.Helper()
+ packet := mqttReadPacket(t, conn)
+ require.Equal(t, byte(0x30), packet[0]&0xf0)
+ index := 1
+ for packet[index]&0x80 != 0 {
+ index++
+ }
+ index++
+ topicLength := int(packet[index])<<8 | int(packet[index+1])
+ index += 2
+ topic := string(packet[index : index+topicLength])
+ index += topicLength
+ return topic, packet[index:]
+}
+
+func mqttReadPacket(t *testing.T, conn net.Conn) []byte {
+ t.Helper()
+ fixed := make([]byte, 1)
+ _, err := io.ReadFull(conn, fixed)
+ require.NoError(t, err)
+ packet := append([]byte{}, fixed...)
+ remaining := 0
+ multiplier := 1
+ for {
+ encoded := make([]byte, 1)
+ _, err = io.ReadFull(conn, encoded)
+ require.NoError(t, err)
+ packet = append(packet, encoded[0])
+ remaining += int(encoded[0]&127) * multiplier
+ multiplier *= 128
+ if encoded[0]&128 == 0 {
+ break
+ }
+ }
+ body := make([]byte, remaining)
+ _, err = io.ReadFull(conn, body)
+ require.NoError(t, err)
+ return append(packet, body...)
+}
+
+func mqttUTF8(value string) []byte {
+ bytes := []byte(value)
+ return append([]byte{byte(len(bytes) >> 8), byte(len(bytes))}, bytes...)
+}
+
+func mqttRemainingLength(length int) []byte {
+ var encoded []byte
+ value := length
+ for {
+ digit := byte(value % 128)
+ value /= 128
+ if value > 0 {
+ digit |= 128
+ }
+ encoded = append(encoded, digit)
+ if value == 0 {
+ return encoded
+ }
+ }
+}
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index d6d9ab7b5f..6756d79517 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -245,6 +245,19 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>pipes</artifactId>
</dependency>
+ <!-- AWS IoT client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>iot</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>iotdataplane</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>iotjobsdataplane</artifactId>
+ </dependency>
<!-- EKS client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index c67ab5a636..cf3b9c1ec2 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -54,6 +54,9 @@ import software.amazon.awssdk.services.codedeploy.CodeDeployClient;
import software.amazon.awssdk.services.codepipeline.CodePipelineClient;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.eks.EksClient;
+import software.amazon.awssdk.services.iot.IotClient;
+import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
+import software.amazon.awssdk.services.iotjobsdataplane.IotJobsDataPlaneClient;
import software.amazon.awssdk.services.scheduler.SchedulerClient;
import software.amazon.awssdk.services.appconfig.AppConfigClient;
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
@@ -668,6 +671,30 @@ public final class TestFixtures {
.build();
}
+ public static IotClient iotClient() {
+ return IotClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
+ public static IotDataPlaneClient iotDataClient() {
+ return IotDataPlaneClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
+ public static IotJobsDataPlaneClient iotJobsDataClient() {
+ return IotJobsDataPlaneClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static ElasticLoadBalancingV2Client elbV2Client() {
return ElasticLoadBalancingV2Client.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
new file mode 100644
index 0000000000..3c8d920b6b
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
@@ -0,0 +1,682 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+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.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.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.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.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.DisableTopicRuleRequest;
+import software.amazon.awssdk.services.iot.model.DeprecateThingTypeRequest;
+import software.amazon.awssdk.services.iot.model.DetachPolicyRequest;
+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.ListCertificatesRequest;
+import software.amazon.awssdk.services.iot.model.ListJobExecutionsForThingRequest;
+import software.amazon.awssdk.services.iot.model.ListJobsRequest;
+import software.amazon.awssdk.services.iot.model.ListPoliciesRequest;
+import software.amazon.awssdk.services.iot.model.ListThingGroupsForThingRequest;
+import software.amazon.awssdk.services.iot.model.ListThingsInThingGroupRequest;
+import software.amazon.awssdk.services.iot.model.ListThingsRequest;
+import software.amazon.awssdk.services.iot.model.ListTagsForResourceRequest;
+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.SqsAction;
+import software.amazon.awssdk.services.iot.model.ResourceAlreadyExistsException;
+import software.amazon.awssdk.services.iot.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.iot.model.Tag;
+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.UntagResourceRequest;
+import software.amazon.awssdk.services.iot.model.UpdateCertificateRequest;
+import software.amazon.awssdk.services.iot.model.UpdateThingRequest;
+import software.amazon.awssdk.services.iot.model.UpdateThingTypeRequest;
+import software.amazon.awssdk.services.iot.model.VersionConflictException;
+import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
+import software.amazon.awssdk.services.iotdataplane.model.DeleteConnectionRequest;
+import software.amazon.awssdk.services.iotdataplane.model.DeleteThingShadowRequest;
+import software.amazon.awssdk.services.iotdataplane.model.GetThingShadowRequest;
+import software.amazon.awssdk.services.iotdataplane.model.ListNamedShadowsForThingRequest;
+import software.amazon.awssdk.services.iotdataplane.model.PublishRequest;
+import software.amazon.awssdk.services.iotdataplane.model.UpdateThingShadowRequest;
+import software.amazon.awssdk.services.iotjobsdataplane.IotJobsDataPlaneClient;
+import software.amazon.awssdk.services.iotjobsdataplane.model.GetPendingJobExecutionsRequest;
+import software.amazon.awssdk.services.iotjobsdataplane.model.JobExecutionStatus;
+import software.amazon.awssdk.services.iotjobsdataplane.model.StartNextPendingJobExecutionRequest;
+import software.amazon.awssdk.services.iotjobsdataplane.model.UpdateJobExecutionRequest;
+import software.amazon.awssdk.services.sqs.SqsClient;
+import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
+import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
+import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("AWS IoT")
+class IotTest {
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+
+ private final IotClient iot = TestFixtures.iotClient();
+ private final IotDataPlaneClient iotData = TestFixtures.iotDataClient();
+ private final IotJobsDataPlaneClient iotJobsData = TestFixtures.iotJobsDataClient();
+ private final SqsClient sqs = TestFixtures.sqsClient();
+
+ @Test
+ void describeEndpoint() {
+ var response = iot.describeEndpoint(DescribeEndpointRequest.builder()
+ .endpointType("iot:Data-ATS")
+ .build());
+
+ assertThat(response.endpointAddress()).isNotBlank();
+ }
+
+ @Test
+ void thingRegistryCrud() {
+ String thingName = "java-iot-thing";
+ String otherThingName = "java-iot-other-thing";
+ try {
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ iot.deleteThing(DeleteThingRequest.builder().thingName(otherThingName).build());
+ } catch (Exception ignored) {
+ }
+
+ assertThatThrownBy(() -> iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build()))
+ .isInstanceOf(ResourceNotFoundException.class);
+
+ var created = iot.createThing(CreateThingRequest.builder()
+ .thingName(thingName)
+ .attributePayload(AttributePayload.builder().attributes(Map.of("env", "java")).build())
+ .build());
+ assertThat(created.thingName()).isEqualTo(thingName);
+ assertThat(created.thingArn()).endsWith(":thing/" + thingName);
+
+ var idempotent = iot.createThing(CreateThingRequest.builder()
+ .thingName(thingName)
+ .attributePayload(AttributePayload.builder().attributes(Map.of("env", "java")).build())
+ .build());
+ assertThat(idempotent.thingName()).isEqualTo(thingName);
+
+ assertThatThrownBy(() -> iot.createThing(CreateThingRequest.builder().thingName(thingName).build()))
+ .isInstanceOf(ResourceAlreadyExistsException.class);
+
+ var described = iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build());
+ assertThat(described.attributes()).containsEntry("env", "java");
+
+ iot.createThing(CreateThingRequest.builder().thingName(otherThingName).build());
+
+ var listed = iot.listThings(ListThingsRequest.builder().build());
+ assertThat(listed.things()).anyMatch(thing -> thingName.equals(thing.thingName()));
+
+ var firstPage = iot.listThings(ListThingsRequest.builder().maxResults(1).build());
+ assertThat(firstPage.things()).hasSize(1);
+ assertThat(firstPage.nextToken()).isNotBlank();
+ var secondPage = iot.listThings(ListThingsRequest.builder()
+ .maxResults(1)
+ .nextToken(firstPage.nextToken())
+ .build());
+ assertThat(secondPage.things()).hasSize(1);
+
+ iot.updateThing(UpdateThingRequest.builder()
+ .thingName(thingName)
+ .attributePayload(AttributePayload.builder()
+ .attributes(Map.of("env", "updated", "owner", "iot"))
+ .build())
+ .build());
+
+ iot.updateThing(UpdateThingRequest.builder()
+ .thingName(thingName)
+ .expectedVersion(2L)
+ .attributePayload(AttributePayload.builder()
+ .attributes(Map.of("env", "versioned", "owner", "iot"))
+ .build())
+ .build());
+
+ assertThatThrownBy(() -> iot.updateThing(UpdateThingRequest.builder()
+ .thingName(thingName)
+ .expectedVersion(2L)
+ .attributePayload(AttributePayload.builder().attributes(Map.of("env", "stale")).build())
+ .build()))
+ .isInstanceOf(VersionConflictException.class);
+
+ var updated = iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build());
+ assertThat(updated.attributes()).containsEntry("env", "versioned").containsEntry("owner", "iot");
+
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ iot.deleteThing(DeleteThingRequest.builder().thingName(otherThingName).build());
+ assertThatThrownBy(() -> iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build()))
+ .isInstanceOf(ResourceNotFoundException.class);
+ }
+
+ @Test
+ void thingTags() {
+ String thingName = "java-iot-tagged-thing";
+ try {
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ } catch (Exception ignored) {
+ }
+
+ var created = iot.createThing(CreateThingRequest.builder().thingName(thingName).build());
+ String thingArn = created.thingArn();
+
+ var emptyTags = iot.listTagsForResource(ListTagsForResourceRequest.builder()
+ .resourceArn(thingArn)
+ .build());
+ assertThat(emptyTags.tags()).isEmpty();
+
+ iot.tagResource(TagResourceRequest.builder()
+ .resourceArn(thingArn)
+ .tags(Tag.builder().key("env").value("java").build(),
+ Tag.builder().key("owner").value("iot").build())
+ .build());
+
+ var tags = iot.listTagsForResource(ListTagsForResourceRequest.builder()
+ .resourceArn(thingArn)
+ .build());
+ assertThat(tags.tags()).extracting(Tag::key).containsExactlyInAnyOrder("env", "owner");
+ assertThat(tags.tags()).extracting(Tag::value).contains("java", "iot");
+
+ iot.untagResource(UntagResourceRequest.builder()
+ .resourceArn(thingArn)
+ .tagKeys("env")
+ .build());
+
+ var remainingTags = iot.listTagsForResource(ListTagsForResourceRequest.builder()
+ .resourceArn(thingArn)
+ .build());
+ assertThat(remainingTags.tags()).extracting(Tag::key).containsExactly("owner");
+
+ assertThatThrownBy(() -> iot.listTagsForResource(ListTagsForResourceRequest.builder()
+ .resourceArn("arn:aws:iot:us-east-1:000000000000:thing/missing-tagged-thing")
+ .build()))
+ .isInstanceOf(ResourceNotFoundException.class);
+ }
+
+ @Test
+ void certificatesPoliciesAndAttachments() {
+ var cert = iot.createKeysAndCertificate(CreateKeysAndCertificateRequest.builder()
+ .setAsActive(true)
+ .build());
+ assertThat(cert.certificatePem()).contains("BEGIN CERTIFICATE");
+ assertThat(cert.keyPair().publicKey()).contains("BEGIN PUBLIC KEY");
+
+ var described = iot.describeCertificate(DescribeCertificateRequest.builder()
+ .certificateId(cert.certificateId())
+ .build());
+ assertThat(described.certificateDescription().status()).isEqualTo(CertificateStatus.ACTIVE);
+
+ var certs = iot.listCertificates(ListCertificatesRequest.builder().build());
+ assertThat(certs.certificates()).anyMatch(item -> cert.certificateArn().equals(item.certificateArn()));
+
+ iot.updateCertificate(UpdateCertificateRequest.builder()
+ .certificateId(cert.certificateId())
+ .newStatus(CertificateStatus.INACTIVE)
+ .build());
+ described = iot.describeCertificate(DescribeCertificateRequest.builder()
+ .certificateId(cert.certificateId())
+ .build());
+ assertThat(described.certificateDescription().status()).isEqualTo(CertificateStatus.INACTIVE);
+
+ String policyName = "java-iot-policy";
+ String policyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
+ var policy = iot.createPolicy(CreatePolicyRequest.builder()
+ .policyName(policyName)
+ .policyDocument(policyDocument)
+ .build());
+ assertThat(policy.policyName()).isEqualTo(policyName);
+
+ var gotPolicy = iot.getPolicy(GetPolicyRequest.builder().policyName(policyName).build());
+ assertThat(gotPolicy.policyDocument()).contains("2012-10-17");
+
+ var policies = iot.listPolicies(ListPoliciesRequest.builder().build());
+ assertThat(policies.policies()).anyMatch(item -> policyName.equals(item.policyName()));
+
+ iot.attachPolicy(AttachPolicyRequest.builder().policyName(policyName).target(cert.certificateArn()).build());
+ iot.detachPolicy(DetachPolicyRequest.builder().policyName(policyName).target(cert.certificateArn()).build());
+
+ String thingName = "java-iot-principal-thing";
+ try {
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ } catch (Exception ignored) {
+ }
+ iot.createThing(CreateThingRequest.builder().thingName(thingName).build());
+ iot.attachThingPrincipal(AttachThingPrincipalRequest.builder()
+ .thingName(thingName)
+ .principal(cert.certificateArn())
+ .build());
+ var principals = iot.listThingPrincipals(ListThingPrincipalsRequest.builder().thingName(thingName).build());
+ assertThat(principals.principals()).contains(cert.certificateArn());
+ iot.detachThingPrincipal(DetachThingPrincipalRequest.builder()
+ .thingName(thingName)
+ .principal(cert.certificateArn())
+ .build());
+ }
+
+ @Test
+ void iotDataShadowsAndPublish() {
+ String thingName = "java-iot-shadow-thing";
+ assertThatThrownBy(() -> iotData.deleteConnection(DeleteConnectionRequest.builder()
+ .clientId("java-iot-missing-client")
+ .build()))
+ .isInstanceOf(software.amazon.awssdk.services.iotdataplane.model.ResourceNotFoundException.class);
+
+ assertThatThrownBy(() -> iotData.getThingShadow(GetThingShadowRequest.builder()
+ .thingName(thingName)
+ .build()))
+ .isInstanceOf(software.amazon.awssdk.services.iotdataplane.model.ResourceNotFoundException.class);
+
+ var updated = iotData.updateThingShadow(UpdateThingShadowRequest.builder()
+ .thingName(thingName)
+ .payload(SdkBytes.fromUtf8String("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"))
+ .build());
+ assertThat(updated.payload().asUtf8String()).contains("\"version\":1");
+
+ iotData.updateThingShadow(UpdateThingShadowRequest.builder()
+ .thingName(thingName)
+ .payload(SdkBytes.fromUtf8String("{\"state\":{\"reported\":{\"color\":\"green\"}}}"))
+ .build());
+ var got = iotData.getThingShadow(GetThingShadowRequest.builder().thingName(thingName).build());
+ assertThat(got.payload().asUtf8String()).contains("blue").contains("green");
+
+ iotData.updateThingShadow(UpdateThingShadowRequest.builder()
+ .thingName(thingName)
+ .shadowName("settings")
+ .payload(SdkBytes.fromUtf8String("{\"state\":{\"desired\":{\"mode\":\"auto\"}}}"))
+ .build());
+ var named = iotData.listNamedShadowsForThing(ListNamedShadowsForThingRequest.builder()
+ .thingName(thingName)
+ .build());
+ assertThat(named.results()).contains("settings");
+
+ iotData.publish(PublishRequest.builder()
+ .topic("devices/" + thingName + "/events")
+ .payload(SdkBytes.fromUtf8String("payload"))
+ .build());
+ iotData.deleteThingShadow(DeleteThingShadowRequest.builder().thingName(thingName).shadowName("settings").build());
+ iotData.deleteThingShadow(DeleteThingShadowRequest.builder().thingName(thingName).build());
+ }
+
+ @Test
+ void topicRuleCrudAndSqsAction() {
+ String ruleName = "java-iot-topic-rule";
+ String queueUrl = sqs.createQueue(CreateQueueRequest.builder()
+ .queueName("java-iot-rule-queue")
+ .build()).queueUrl();
+
+ try {
+ iot.createTopicRule(CreateTopicRuleRequest.builder()
+ .ruleName(ruleName)
+ .topicRulePayload(TopicRulePayload.builder()
+ .sql("SELECT * FROM 'devices/java-iot/rules'")
+ .description("java topic rule")
+ .ruleDisabled(false)
+ .actions(Action.builder()
+ .sqs(SqsAction.builder()
+ .roleArn("arn:aws:iam::000000000000:role/iot-rule-role")
+ .queueUrl(queueUrl)
+ .useBase64(false)
+ .build())
+ .build())
+ .build())
+ .build());
+
+ var got = iot.getTopicRule(GetTopicRuleRequest.builder().ruleName(ruleName).build());
+ assertThat(got.rule().ruleName()).isEqualTo(ruleName);
+ assertThat(got.rule().actions().get(0).sqs().queueUrl()).isEqualTo(queueUrl);
+
+ iot.disableTopicRule(DisableTopicRuleRequest.builder().ruleName(ruleName).build());
+ var listed = iot.listTopicRules(ListTopicRulesRequest.builder().build());
+ assertThat(listed.rules()).anyMatch(rule -> ruleName.equals(rule.ruleName()) && rule.ruleDisabled());
+
+ iot.enableTopicRule(EnableTopicRuleRequest.builder().ruleName(ruleName).build());
+ iotData.publish(PublishRequest.builder()
+ .topic("devices/java-iot/rules")
+ .payload(SdkBytes.fromUtf8String("java-rule-payload"))
+ .build());
+
+ var received = sqs.receiveMessage(ReceiveMessageRequest.builder()
+ .queueUrl(queueUrl)
+ .maxNumberOfMessages(1)
+ .build());
+ assertThat(received.messages()).hasSize(1);
+ assertThat(received.messages().get(0).body()).isEqualTo("java-rule-payload");
+ } finally {
+ try {
+ iot.deleteTopicRule(DeleteTopicRuleRequest.builder().ruleName(ruleName).build());
+ } catch (Exception ignored) {
+ }
+ sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build());
+ }
+ }
+
+ @Test
+ void thingTypesGroupsAndJobs() {
+ String thingType = "java-iot-type";
+ String thingName = "java-iot-typed-thing";
+ String groupName = "java-iot-group";
+ String jobId = "java-iot-job";
+ try {
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ } catch (Exception ignored) {
+ }
+ try {
+ iot.deleteThingGroup(DeleteThingGroupRequest.builder().thingGroupName(groupName).build());
+ } catch (Exception ignored) {
+ }
+ try {
+ iot.deprecateThingType(DeprecateThingTypeRequest.builder().thingTypeName(thingType).build());
+ iot.deleteThingType(DeleteThingTypeRequest.builder().thingTypeName(thingType).build());
+ } catch (Exception ignored) {
+ }
+
+ var jobsEndpoint = iot.describeEndpoint(DescribeEndpointRequest.builder().endpointType("iot:Jobs").build());
+ assertThat(jobsEndpoint.endpointAddress()).isNotBlank();
+
+ var createdType = iot.createThingType(CreateThingTypeRequest.builder()
+ .thingTypeName(thingType)
+ .thingTypeProperties(ThingTypeProperties.builder()
+ .thingTypeDescription("java type")
+ .searchableAttributes("model")
+ .build())
+ .build());
+ assertThat(createdType.thingTypeName()).isEqualTo(thingType);
+ var describedType = iot.describeThingType(DescribeThingTypeRequest.builder().thingTypeName(thingType).build());
+ assertThat(describedType.thingTypeProperties().thingTypeDescription()).isEqualTo("java type");
+ assertThat(iot.listThingTypes(ListThingTypesRequest.builder().build()).thingTypes())
+ .anyMatch(type -> thingType.equals(type.thingTypeName()));
+
+ iot.updateThingType(UpdateThingTypeRequest.builder()
+ .thingTypeName(thingType)
+ .thingTypeProperties(ThingTypeProperties.builder()
+ .thingTypeDescription("java type updated")
+ .searchableAttributes("model", "fw")
+ .build())
+ .build());
+
+ var createdThing = iot.createThing(CreateThingRequest.builder()
+ .thingName(thingName)
+ .thingTypeName(thingType)
+ .attributePayload(AttributePayload.builder().attributes(Map.of("model", "j1")).build())
+ .build());
+ assertThat(iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build()).thingTypeName()).isEqualTo(thingType);
+
+ var createdGroup = iot.createThingGroup(CreateThingGroupRequest.builder()
+ .thingGroupName(groupName)
+ .thingGroupProperties(ThingGroupProperties.builder()
+ .thingGroupDescription("java group")
+ .attributePayload(AttributePayload.builder().attributes(Map.of("fleet", "java")).build())
+ .build())
+ .build());
+ assertThat(createdGroup.thingGroupName()).isEqualTo(groupName);
+ iot.addThingToThingGroup(AddThingToThingGroupRequest.builder().thingGroupName(groupName).thingName(thingName).build());
+ assertThat(iot.listThingsInThingGroup(ListThingsInThingGroupRequest.builder().thingGroupName(groupName).build()).things()).contains(thingName);
+ assertThat(iot.listThingGroupsForThing(ListThingGroupsForThingRequest.builder().thingName(thingName).build()).thingGroups())
+ .anyMatch(group -> groupName.equals(group.groupName()));
+
+ var createdJob = iot.createJob(CreateJobRequest.builder()
+ .jobId(jobId)
+ .targets(createdThing.thingArn())
+ .document("{\"operation\":\"reboot\"}")
+ .description("java job")
+ .build());
+ assertThat(createdJob.jobId()).isEqualTo(jobId);
+ assertThat(iot.describeJob(DescribeJobRequest.builder().jobId(jobId).build()).job().statusAsString()).isEqualTo("IN_PROGRESS");
+ assertThat(iot.listJobs(ListJobsRequest.builder().build()).jobs()).anyMatch(job -> jobId.equals(job.jobId()));
+ assertThat(iot.listJobExecutionsForThing(ListJobExecutionsForThingRequest.builder().thingName(thingName).build()).executionSummaries())
+ .anyMatch(execution -> jobId.equals(execution.jobId()));
+
+ var pending = iotJobsData.getPendingJobExecutions(GetPendingJobExecutionsRequest.builder().thingName(thingName).build());
+ assertThat(pending.queuedJobs()).anyMatch(job -> jobId.equals(job.jobId()));
+ var started = iotJobsData.startNextPendingJobExecution(StartNextPendingJobExecutionRequest.builder()
+ .thingName(thingName)
+ .statusDetails(Map.of("phase", "download"))
+ .build());
+ assertThat(started.execution().status()).isEqualTo(JobExecutionStatus.IN_PROGRESS);
+ var updated = iotJobsData.updateJobExecution(UpdateJobExecutionRequest.builder()
+ .thingName(thingName)
+ .jobId(jobId)
+ .status(JobExecutionStatus.SUCCEEDED)
+ .expectedVersion(2L)
+ .includeJobExecutionState(true)
+ .includeJobDocument(true)
+ .build());
+ assertThat(updated.executionState().status()).isEqualTo(JobExecutionStatus.SUCCEEDED);
+ assertThat(updated.jobDocument()).contains("reboot");
+
+ iot.removeThingFromThingGroup(RemoveThingFromThingGroupRequest.builder().thingGroupName(groupName).thingName(thingName).build());
+ iot.deleteThingGroup(DeleteThingGroupRequest.builder().thingGroupName(groupName).build());
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ iot.deprecateThingType(DeprecateThingTypeRequest.builder().thingTypeName(thingType).build());
+ iot.deleteThingType(DeleteThingTypeRequest.builder().thingTypeName(thingType).build());
+ }
+
+ @Test
+ void mqttConnectPublishSubscribe() throws Exception {
+ String topic = "devices/java-iot-mqtt/events";
+ byte[] payload = "java-mqtt".getBytes(StandardCharsets.UTF_8);
+
+ try (Socket subscriber = mqttConnect("java-iot-mqtt-sub")) {
+ mqttSubscribe(subscriber, topic);
+ try (Socket publisher = mqttConnect("java-iot-mqtt-pub")) {
+ mqttPublish(publisher, topic, payload);
+ }
+
+ MqttPublish received = mqttReadPublish(subscriber.getInputStream());
+ assertThat(received.topic()).isEqualTo(topic);
+ assertThat(received.payload()).isEqualTo(payload);
+ }
+ }
+
+ @Test
+ void mqtt5Connect() throws Exception {
+ try (Socket client = mqtt5Connect("java-iot-mqtt5")) {
+ assertThat(client.isConnected()).isTrue();
+ }
+ }
+
+ @Test
+ void mqttShadowReservedTopics() throws Exception {
+ String thingName = "java-iot-shadow";
+ try (Socket subscriber = mqttConnect("java-iot-shadow-sub")) {
+ mqttSubscribe(subscriber, "$aws/things/" + thingName + "/shadow/update/accepted");
+ mqttSubscribe(subscriber, "$aws/things/" + thingName + "/shadow/get/accepted");
+ mqttSubscribe(subscriber, "$aws/things/" + thingName + "/shadow/delete/accepted");
+
+ try (Socket publisher = mqttConnect("java-iot-shadow-pub")) {
+ mqttPublish(publisher, "$aws/things/" + thingName + "/shadow/update",
+ "{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"update-token\"}".getBytes(StandardCharsets.UTF_8));
+ MqttPublish accepted = mqttReadPublish(subscriber.getInputStream());
+ assertThat(accepted.topic()).isEqualTo("$aws/things/" + thingName + "/shadow/update/accepted");
+ JsonNode acceptedPayload = OBJECT_MAPPER.readTree(accepted.payload());
+ assertThat(acceptedPayload.path("clientToken").asText()).isEqualTo("update-token");
+
+ mqttPublish(publisher, "$aws/things/" + thingName + "/shadow/get",
+ "{\"clientToken\":\"get-token\"}".getBytes(StandardCharsets.UTF_8));
+ MqttPublish got = mqttReadPublish(subscriber.getInputStream());
+ assertThat(got.topic()).isEqualTo("$aws/things/" + thingName + "/shadow/get/accepted");
+ JsonNode gotPayload = OBJECT_MAPPER.readTree(got.payload());
+ assertThat(gotPayload.path("clientToken").asText()).isEqualTo("get-token");
+
+ mqttPublish(publisher, "$aws/things/" + thingName + "/shadow/delete",
+ "{\"clientToken\":\"delete-token\"}".getBytes(StandardCharsets.UTF_8));
+ MqttPublish deleted = mqttReadPublish(subscriber.getInputStream());
+ assertThat(deleted.topic()).isEqualTo("$aws/things/" + thingName + "/shadow/delete/accepted");
+ JsonNode deletedPayload = OBJECT_MAPPER.readTree(deleted.payload());
+ assertThat(deletedPayload.path("clientToken").asText()).isEqualTo("delete-token");
+ }
+ }
+ }
+
+ private Socket mqttConnect(String clientId) throws IOException {
+ Socket socket = new Socket();
+ socket.connect(new InetSocketAddress("floci", 1883), 5_000);
+ socket.setSoTimeout(5_000);
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ mqttUtf8(body, "MQTT");
+ body.write(0x04);
+ body.write(0x02);
+ body.write(0x00);
+ body.write(0x3c);
+ mqttUtf8(body, clientId);
+ socket.getOutputStream().write(mqttPacket(0x10, body.toByteArray()));
+ assertThat(mqttReadPacket(socket.getInputStream())).containsExactly(0x20, 0x02, 0x00, 0x00);
+ return socket;
+ }
+
+ private Socket mqtt5Connect(String clientId) throws IOException {
+ Socket socket = new Socket();
+ socket.connect(new InetSocketAddress("floci", 1883), 5_000);
+ socket.setSoTimeout(5_000);
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ mqttUtf8(body, "MQTT");
+ body.write(0x05);
+ body.write(0x02);
+ body.write(0x00);
+ body.write(0x3c);
+ body.write(0x00);
+ mqttUtf8(body, clientId);
+ socket.getOutputStream().write(mqttPacket(0x10, body.toByteArray()));
+ mqttAssertV5Connack(mqttReadPacket(socket.getInputStream()));
+ return socket;
+ }
+
+ private void mqttAssertV5Connack(byte[] packet) {
+ assertThat(packet[0] & 0xff).isEqualTo(0x20);
+ int index = 1;
+ while ((packet[index] & 0x80) != 0) {
+ index++;
+ }
+ index++;
+ assertThat(packet[index] & 0xff).isEqualTo(0x00);
+ assertThat(packet[index + 1] & 0xff).isEqualTo(0x00);
+ }
+
+ private void mqttSubscribe(Socket socket, String topic) throws IOException {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.write(0x00);
+ body.write(0x01);
+ mqttUtf8(body, topic);
+ body.write(0x00);
+ socket.getOutputStream().write(mqttPacket(0x82, body.toByteArray()));
+ assertThat(mqttReadPacket(socket.getInputStream())).containsExactly(0x90, 0x03, 0x00, 0x01, 0x00);
+ }
+
+ private void mqttPublish(Socket socket, String topic, byte[] payload) throws IOException {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ mqttUtf8(body, topic);
+ body.write(payload);
+ socket.getOutputStream().write(mqttPacket(0x30, body.toByteArray()));
+ }
+
+ private MqttPublish mqttReadPublish(InputStream input) throws IOException {
+ byte[] packet = mqttReadPacket(input);
+ assertThat(packet[0] & 0xf0).isEqualTo(0x30);
+ int index = 1;
+ while ((packet[index] & 0x80) != 0) {
+ index++;
+ }
+ index++;
+ int topicLength = ((packet[index] & 0xff) << 8) | (packet[index + 1] & 0xff);
+ index += 2;
+ String topic = new String(packet, index, topicLength, StandardCharsets.UTF_8);
+ index += topicLength;
+ return new MqttPublish(topic, Arrays.copyOfRange(packet, index, packet.length));
+ }
+
+ private byte[] mqttPacket(int type, byte[] body) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(type);
+ mqttRemainingLength(out, body.length);
+ out.write(body);
+ return out.toByteArray();
+ }
+
+ private byte[] mqttReadPacket(InputStream input) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ int first = input.read();
+ if (first < 0) {
+ throw new IOException("No MQTT packet received");
+ }
+ out.write(first);
+
+ int multiplier = 1;
+ int remainingLength = 0;
+ int encoded;
+ do {
+ encoded = input.read();
+ if (encoded < 0) {
+ throw new IOException("Incomplete MQTT remaining length");
+ }
+ out.write(encoded);
+ remainingLength += (encoded & 127) * multiplier;
+ multiplier *= 128;
+ } while ((encoded & 128) != 0);
+
+ byte[] body = input.readNBytes(remainingLength);
+ if (body.length != remainingLength) {
+ throw new IOException("Incomplete MQTT packet body");
+ }
+ out.write(body);
+ return out.toByteArray();
+ }
+
+ private void mqttUtf8(OutputStream out, String value) throws IOException {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ out.write((bytes.length >>> 8) & 0xff);
+ out.write(bytes.length & 0xff);
+ out.write(bytes);
+ }
+
+ private void mqttRemainingLength(OutputStream out, int length) throws IOException {
+ int value = length;
+ do {
+ int encoded = value % 128;
+ value /= 128;
+ if (value > 0) {
+ encoded |= 128;
+ }
+ out.write(encoded);
+ } while (value > 0);
+ }
+
+ private record MqttPublish(String topic, byte[] payload) {
+ }
+}
diff --git a/compatibility-tests/sdk-test-python/conftest.py b/compatibility-tests/sdk-test-python/conftest.py
index 072027a379..21a121a0f8 100644
--- a/compatibility-tests/sdk-test-python/conftest.py
+++ b/compatibility-tests/sdk-test-python/conftest.py
@@ -181,6 +181,24 @@ def sesv2_client(aws_config, client_config):
return boto3.client("sesv2", config=client_config, **aws_config)
+def iot_client(aws_config, client_config):
+ """Create AWS IoT client."""
+ return boto3.client("iot", config=client_config, **aws_config)
+
+
+def iot_data_client(aws_config, client_config):
+ """Create AWS IoT Data client."""
+ return boto3.client("iot-data", config=client_config, **aws_config)
+
+
+def iot_jobs_data_client(aws_config, client_config):
+ """Create AWS IoT Jobs Data client."""
+ return boto3.client("iot-jobs-data", config=client_config, **aws_config)
+
+
# ============================================
# Utility Fixtures
# ============================================
diff --git a/compatibility-tests/sdk-test-python/tests/test_iot.py b/compatibility-tests/sdk-test-python/tests/test_iot.py
new file mode 100644
index 0000000000..484bb0a3e5
--- /dev/null
+++ b/compatibility-tests/sdk-test-python/tests/test_iot.py
@@ -0,0 +1,597 @@
+from botocore.exceptions import ClientError
+import json
+import socket
+import struct
+
+
+def test_describe_endpoint(iot_client):
+ response = iot_client.describe_endpoint(endpointType="iot:Data-ATS")
+
+ assert response["endpointAddress"]
+
+
+def test_thing_registry_crud(iot_client, unique_name):
+ thing_name = f"{unique_name}-thing"
+ other_thing_name = f"{unique_name}-other-thing"
+
+ missing = False
+ try:
+ iot_client.describe_thing(thingName=thing_name)
+ except ClientError as exc:
+ missing = exc.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert missing
+
+ created = iot_client.create_thing(
+ thingName=thing_name,
+ attributePayload={"attributes": {"env": "python"}},
+ )
+ assert created["thingName"] == thing_name
+ assert created["thingArn"].endswith(f":thing/{thing_name}")
+
+ idempotent = iot_client.create_thing(
+ thingName=thing_name,
+ attributePayload={"attributes": {"env": "python"}},
+ )
+ assert idempotent["thingName"] == thing_name
+
+ try:
+ iot_client.create_thing(thingName=thing_name)
+ raise AssertionError("duplicate create should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceAlreadyExistsException"
+
+ described = iot_client.describe_thing(thingName=thing_name)
+ assert described["attributes"]["env"] == "python"
+
+ iot_client.create_thing(thingName=other_thing_name)
+
+ listed = iot_client.list_things()
+ assert any(thing["thingName"] == thing_name for thing in listed["things"])
+
+ first_page = iot_client.list_things(maxResults=1)
+ assert len(first_page["things"]) == 1
+ assert first_page.get("nextToken")
+ second_page = iot_client.list_things(maxResults=1, nextToken=first_page["nextToken"])
+ assert len(second_page["things"]) == 1
+
+ iot_client.update_thing(
+ thingName=thing_name,
+ attributePayload={"attributes": {"env": "updated", "owner": "iot"}},
+ )
+ iot_client.update_thing(
+ thingName=thing_name,
+ expectedVersion=2,
+ attributePayload={"attributes": {"env": "versioned", "owner": "iot"}},
+ )
+ try:
+ iot_client.update_thing(
+ thingName=thing_name,
+ expectedVersion=2,
+ attributePayload={"attributes": {"env": "stale"}},
+ )
+ raise AssertionError("stale expectedVersion should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "VersionConflictException"
+
+ updated = iot_client.describe_thing(thingName=thing_name)
+ assert updated["attributes"] == {"env": "versioned", "owner": "iot"}
+
+ iot_client.delete_thing(thingName=thing_name)
+ iot_client.delete_thing(thingName=other_thing_name)
+ try:
+ iot_client.describe_thing(thingName=thing_name)
+ raise AssertionError("describe after delete should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_thing_tags(iot_client, unique_name):
+ thing_name = f"{unique_name}-tagged-thing"
+
+ created = iot_client.create_thing(thingName=thing_name)
+ thing_arn = created["thingArn"]
+
+ listed = iot_client.list_tags_for_resource(resourceArn=thing_arn)
+ assert listed["tags"] == []
+
+ iot_client.tag_resource(
+ resourceArn=thing_arn,
+ tags=[{"Key": "env", "Value": "python"}, {"Key": "owner", "Value": "iot"}],
+ )
+ tags = iot_client.list_tags_for_resource(resourceArn=thing_arn)["tags"]
+ assert {tag["Key"]: tag["Value"] for tag in tags} == {"env": "python", "owner": "iot"}
+
+ iot_client.untag_resource(resourceArn=thing_arn, tagKeys=["env"])
+ tags = iot_client.list_tags_for_resource(resourceArn=thing_arn)["tags"]
+ assert {tag["Key"]: tag["Value"] for tag in tags} == {"owner": "iot"}
+
+ try:
+ iot_client.list_tags_for_resource(
+ resourceArn="arn:aws:iot:us-east-1:000000000000:thing/missing-tagged-thing"
+ )
+ raise AssertionError("listing tags on a missing thing should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_certificates_policies_and_attachments(iot_client, unique_name):
+ created_cert = iot_client.create_keys_and_certificate(setAsActive=True)
+ cert_id = created_cert["certificateId"]
+ cert_arn = created_cert["certificateArn"]
+ assert "BEGIN CERTIFICATE" in created_cert["certificatePem"]
+ assert "PublicKey" in created_cert["keyPair"]
+ assert "PrivateKey" in created_cert["keyPair"]
+
+ described = iot_client.describe_certificate(certificateId=cert_id)
+ assert described["certificateDescription"]["status"] == "ACTIVE"
+
+ listed = iot_client.list_certificates()
+ assert any(cert["certificateArn"] == cert_arn for cert in listed["certificates"])
+
+ iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ described = iot_client.describe_certificate(certificateId=cert_id)
+ assert described["certificateDescription"]["status"] == "INACTIVE"
+
+ policy_name = f"{unique_name}-policy"
+ policy_document = json.dumps({"Version": "2012-10-17", "Statement": []})
+ created_policy = iot_client.create_policy(policyName=policy_name, policyDocument=policy_document)
+ assert created_policy["policyName"] == policy_name
+
+ got_policy = iot_client.get_policy(policyName=policy_name)
+ assert json.loads(got_policy["policyDocument"])["Version"] == "2012-10-17"
+
+ listed_policies = iot_client.list_policies()
+ assert any(policy["policyName"] == policy_name for policy in listed_policies["policies"])
+
+ iot_client.attach_policy(policyName=policy_name, target=cert_arn)
+ iot_client.detach_policy(policyName=policy_name, target=cert_arn)
+
+ thing_name = f"{unique_name}-principal-thing"
+ iot_client.create_thing(thingName=thing_name)
+ iot_client.attach_thing_principal(thingName=thing_name, principal=cert_arn)
+ principals = iot_client.list_thing_principals(thingName=thing_name)
+ assert cert_arn in principals["principals"]
+ principal_things = iot_client.list_principal_things(principal=cert_arn)
+ assert thing_name in principal_things["things"]
+ iot_client.detach_thing_principal(thingName=thing_name, principal=cert_arn)
+
+
+def test_certificate_delete_csr_policy_versions_and_attachment_reads(iot_client, unique_name):
+ active_cert = iot_client.create_keys_and_certificate(setAsActive=True)
+ try:
+ iot_client.delete_certificate(certificateId=active_cert["certificateId"])
+ raise AssertionError("active certificate delete should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidRequestException"
+
+ try:
+ iot_client.update_certificate(
+ certificateId=active_cert["certificateId"], newStatus="PENDING_TRANSFER"
+ )
+ raise AssertionError("unsupported certificate status should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidRequestException"
+
+ iot_client.update_certificate(certificateId=active_cert["certificateId"], newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=active_cert["certificateId"])
+ try:
+ iot_client.describe_certificate(certificateId=active_cert["certificateId"])
+ raise AssertionError("deleted certificate should be missing")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ csr_cert = iot_client.create_certificate_from_csr(
+ certificateSigningRequest="-----BEGIN CERTIFICATE REQUEST-----\nfloci\n-----END CERTIFICATE REQUEST-----",
+ setAsActive=False,
+ )
+ assert "BEGIN CERTIFICATE" in csr_cert["certificatePem"]
+
+ policy_name = f"{unique_name}-versioned-policy"
+ policy_document = json.dumps({"Version": "2012-10-17", "Statement": []})
+ iot_client.create_policy(policyName=policy_name, policyDocument=policy_document)
+ try:
+ iot_client.create_policy(policyName=policy_name, policyDocument=policy_document)
+ raise AssertionError("duplicate policy create should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceAlreadyExistsException"
+
+ version = iot_client.create_policy_version(
+ policyName=policy_name,
+ policyDocument=json.dumps(
+ {"Version": "2012-10-17", "Statement": [{"Effect": "Allow"}]}
+ ),
+ setAsDefault=True,
+ )
+ version_id = version["policyVersionId"]
+ listed_versions = iot_client.list_policy_versions(policyName=policy_name)
+ assert any(item["versionId"] == version_id for item in listed_versions["policyVersions"])
+ got_version = iot_client.get_policy_version(policyName=policy_name, policyVersionId=version_id)
+ assert "Allow" in got_version["policyDocument"]
+
+ iot_client.set_default_policy_version(policyName=policy_name, policyVersionId="1")
+ iot_client.delete_policy_version(policyName=policy_name, policyVersionId=version_id)
+
+ iot_client.attach_policy(policyName=policy_name, target=csr_cert["certificateArn"])
+ attached = iot_client.list_attached_policies(target=csr_cert["certificateArn"])
+ assert any(policy["policyName"] == policy_name for policy in attached["policies"])
+ targets = iot_client.list_targets_for_policy(policyName=policy_name)
+ assert csr_cert["certificateArn"] in targets["targets"]
+ try:
+ iot_client.delete_policy(policyName=policy_name)
+ raise AssertionError("attached policy delete should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidRequestException"
+
+ iot_client.detach_policy(policyName=policy_name, target=csr_cert["certificateArn"])
+ iot_client.delete_policy(policyName=policy_name)
+ try:
+ iot_client.get_policy(policyName=policy_name)
+ raise AssertionError("deleted policy should be missing")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+ iot_client.delete_certificate(certificateId=csr_cert["certificateId"])
+
+
+def test_iot_data_shadows_and_publish(iot_data_client, unique_name):
+ thing_name = f"{unique_name}-shadow-thing"
+
+ try:
+ iot_data_client.get_thing_shadow(thingName=thing_name)
+ raise AssertionError("missing shadow should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ updated = iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ payload=json.dumps({"state": {"desired": {"color": "blue"}}}).encode(),
+ )
+ assert json.loads(updated["payload"].read())["version"] == 1
+
+ iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ payload=json.dumps({"state": {"reported": {"color": "green"}}}).encode(),
+ )
+ got = json.loads(iot_data_client.get_thing_shadow(thingName=thing_name)["payload"].read())
+ assert got["state"]["desired"]["color"] == "blue"
+ assert got["state"]["reported"]["color"] == "green"
+
+ iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ shadowName="settings",
+ payload=json.dumps({"state": {"desired": {"mode": "auto"}}}).encode(),
+ )
+ named = iot_data_client.list_named_shadows_for_thing(thingName=thing_name)
+ assert "settings" in named["results"]
+
+ iot_data_client.publish(topic=f"devices/{thing_name}/events", payload=b"payload")
+ iot_data_client.delete_thing_shadow(thingName=thing_name, shadowName="settings")
+ iot_data_client.delete_thing_shadow(thingName=thing_name)
+
+
+def test_iot_data_retained_messages_and_shadow_conflicts(iot_data_client, unique_name):
+ topic = f"devices/{unique_name}/retained"
+ iot_data_client.publish(topic=topic, payload=b"retained-payload", retain=True, qos=1)
+ retained = iot_data_client.get_retained_message(topic=topic)
+ assert retained["topic"] == topic
+ assert retained["payload"] == b"retained-payload"
+ assert retained["qos"] == 1
+
+ other_topic = f"devices/{unique_name}/retained-other"
+ iot_data_client.publish(topic=other_topic, payload=b"other", retain=True)
+ first_page = iot_data_client.list_retained_messages(maxResults=1)
+ assert len(first_page["retainedTopics"]) == 1
+ assert first_page.get("nextToken")
+ second_page = iot_data_client.list_retained_messages(maxResults=1, nextToken=first_page["nextToken"])
+ assert len(second_page["retainedTopics"]) == 1
+
+ iot_data_client.publish(topic=topic, payload=b"", retain=True)
+ try:
+ iot_data_client.get_retained_message(topic=topic)
+ raise AssertionError("empty retained publish should delete retained message")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ thing_name = f"{unique_name}-shadow-version"
+ iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ payload=json.dumps({"state": {"desired": {"color": "blue", "mode": "auto"}}}).encode(),
+ )
+ updated = iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ payload=json.dumps({"version": 1, "state": {"desired": {"color": None}}}).encode(),
+ )
+ document = json.loads(updated["payload"].read())
+ assert "color" not in document["state"]["desired"]
+ assert document["state"]["desired"]["mode"] == "auto"
+ try:
+ iot_data_client.update_thing_shadow(
+ thingName=thing_name,
+ payload=json.dumps({"version": 1, "state": {"desired": {"mode": "manual"}}}).encode(),
+ )
+ raise AssertionError("stale shadow update should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "VersionConflictException"
+
+
+def test_topic_rule_crud_and_sqs_action(iot_client, iot_data_client, sqs_client, unique_name):
+ rule_name = f"{unique_name}-rule"
+ queue_name = f"{unique_name}-iot-rule-queue"
+ queue_url = sqs_client.create_queue(QueueName=queue_name)["QueueUrl"]
+
+ try:
+ iot_client.create_topic_rule(
+ ruleName=rule_name,
+ topicRulePayload={
+ "sql": f"SELECT * FROM 'devices/{unique_name}/rules'",
+ "description": "python topic rule",
+ "ruleDisabled": False,
+ "actions": [
+ {
+ "sqs": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "queueUrl": queue_url,
+ "useBase64": False,
+ }
+ }
+ ],
+ },
+ )
+
+ got = iot_client.get_topic_rule(ruleName=rule_name)
+ assert got["rule"]["ruleName"] == rule_name
+ assert got["rule"]["sql"] == f"SELECT * FROM 'devices/{unique_name}/rules'"
+ assert got["rule"]["actions"][0]["sqs"]["queueUrl"] == queue_url
+
+ try:
+ iot_client.create_topic_rule(
+ ruleName=rule_name,
+ topicRulePayload={"sql": f"SELECT * FROM 'devices/{unique_name}/rules'", "actions": []},
+ )
+ raise AssertionError("duplicate topic rule create should fail")
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceAlreadyExistsException"
+
+ iot_client.replace_topic_rule(
+ ruleName=rule_name,
+ topicRulePayload={"sql": f"SELECT * FROM 'devices/{unique_name}/rules'", "actions": got["rule"]["actions"]},
+ )
+
+ iot_client.disable_topic_rule(ruleName=rule_name)
+ listed = iot_client.list_topic_rules()
+ assert any(rule["ruleName"] == rule_name and rule["ruleDisabled"] for rule in listed["rules"])
+
+ iot_client.enable_topic_rule(ruleName=rule_name)
+ iot_data_client.publish(topic=f"devices/{unique_name}/rules", payload=b"python-rule-payload")
+
+ received = sqs_client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)
+ assert received["Messages"][0]["Body"] == "python-rule-payload"
+ finally:
+ try:
+ iot_client.delete_topic_rule(ruleName=rule_name)
+ except ClientError:
+ pass
+ sqs_client.delete_queue(QueueUrl=queue_url)
+
+
+def test_thing_types_groups_and_jobs(iot_client, iot_jobs_data_client, unique_name):
+ thing_type = f"{unique_name}-type"
+ thing_name = f"{unique_name}-typed-thing"
+ group_name = f"{unique_name}-group"
+ job_id = f"{unique_name}-job"
+
+ endpoint = iot_client.describe_endpoint(endpointType="iot:Jobs")
+ assert endpoint["endpointAddress"]
+
+ created_type = iot_client.create_thing_type(
+ thingTypeName=thing_type,
+ thingTypeProperties={"thingTypeDescription": "python type", "searchableAttributes": ["model"]},
+ )
+ assert created_type["thingTypeName"] == thing_type
+ described_type = iot_client.describe_thing_type(thingTypeName=thing_type)
+ assert described_type["thingTypeProperties"]["thingTypeDescription"] == "python type"
+ assert "model" in described_type["thingTypeProperties"]["searchableAttributes"]
+ assert any(item["thingTypeName"] == thing_type for item in iot_client.list_thing_types()["thingTypes"])
+
+ iot_client.update_thing_type(
+ thingTypeName=thing_type,
+ thingTypeProperties={"thingTypeDescription": "python type updated", "searchableAttributes": ["model", "fw"]},
+ )
+ thing = iot_client.create_thing(
+ thingName=thing_name,
+ thingTypeName=thing_type,
+ attributePayload={"attributes": {"model": "p1"}},
+ )
+ thing_arn = thing["thingArn"]
+ assert iot_client.describe_thing(thingName=thing_name)["thingTypeName"] == thing_type
+
+ group = iot_client.create_thing_group(
+ thingGroupName=group_name,
+ thingGroupProperties={
+ "thingGroupDescription": "python group",
+ "attributePayload": {"attributes": {"fleet": "python"}},
+ },
+ )
+ assert group["thingGroupName"] == group_name
+ described_group = iot_client.describe_thing_group(thingGroupName=group_name)
+ assert described_group["thingGroupProperties"]["attributePayload"]["attributes"]["fleet"] == "python"
+ iot_client.add_thing_to_thing_group(thingGroupName=group_name, thingName=thing_name)
+ assert thing_name in iot_client.list_things_in_thing_group(thingGroupName=group_name)["things"]
+ assert any(item["groupName"] == group_name for item in iot_client.list_thing_groups_for_thing(thingName=thing_name)["thingGroups"])
+
+ created_job = iot_client.create_job(
+ jobId=job_id,
+ targets=[thing_arn],
+ document=json.dumps({"operation": "reboot"}),
+ description="python job",
+ )
+ assert created_job["jobId"] == job_id
+ assert iot_client.describe_job(jobId=job_id)["job"]["status"] == "IN_PROGRESS"
+ assert any(job["jobId"] == job_id for job in iot_client.list_jobs()["jobs"])
+ assert any(item["jobId"] == job_id for item in iot_client.list_job_executions_for_thing(thingName=thing_name)["executionSummaries"])
+
+ pending = iot_jobs_data_client.get_pending_job_executions(thingName=thing_name)
+ assert any(job["jobId"] == job_id for job in pending["queuedJobs"])
+ started = iot_jobs_data_client.start_next_pending_job_execution(
+ thingName=thing_name,
+ statusDetails={"phase": "download"},
+ )
+ assert started["execution"]["status"] == "IN_PROGRESS"
+ updated = iot_jobs_data_client.update_job_execution(
+ thingName=thing_name,
+ jobId=job_id,
+ status="SUCCEEDED",
+ expectedVersion=2,
+ includeJobExecutionState=True,
+ includeJobDocument=True,
+ )
+ assert updated["executionState"]["status"] == "SUCCEEDED"
+ assert json.loads(updated["jobDocument"])["operation"] == "reboot"
+
+ iot_client.remove_thing_from_thing_group(thingGroupName=group_name, thingName=thing_name)
+ iot_client.delete_thing_group(thingGroupName=group_name)
+ iot_client.delete_thing(thingName=thing_name)
+ iot_client.deprecate_thing_type(thingTypeName=thing_type)
+ iot_client.delete_thing_type(thingTypeName=thing_type)
+
+
+def test_mqtt_connect_publish_subscribe(unique_name):
+ topic = f"devices/{unique_name}/mqtt"
+ payload = b"python-mqtt"
+
+ with mqtt_connect(f"{unique_name}-sub") as subscriber:
+ mqtt_subscribe(subscriber, topic)
+ with mqtt_connect(f"{unique_name}-pub") as publisher:
+ mqtt_publish(publisher, topic, payload)
+ received_topic, received_payload = mqtt_read_publish(subscriber)
+
+ assert received_topic == topic
+ assert received_payload == payload
+
+
+def test_mqtt5_connect(unique_name):
+ with mqtt5_connect(f"{unique_name}-mqtt5") as client:
+ assert client
+
+
+def test_mqtt_shadow_reserved_topics(unique_name):
+ thing_name = f"{unique_name}-shadow"
+ with mqtt_connect(f"{unique_name}-shadow-sub") as subscriber:
+ mqtt_subscribe(subscriber, f"$aws/things/{thing_name}/shadow/update/accepted")
+ mqtt_subscribe(subscriber, f"$aws/things/{thing_name}/shadow/get/accepted")
+ mqtt_subscribe(subscriber, f"$aws/things/{thing_name}/shadow/delete/accepted")
+
+ with mqtt_connect(f"{unique_name}-shadow-pub") as publisher:
+ mqtt_publish(
+ publisher,
+ f"$aws/things/{thing_name}/shadow/update",
+ json.dumps({"state": {"desired": {"color": "blue"}}, "clientToken": "update-token"}).encode(),
+ )
+ topic, payload = mqtt_read_publish(subscriber)
+ assert topic == f"$aws/things/{thing_name}/shadow/update/accepted"
+ accepted = json.loads(payload)
+ assert accepted["state"]["desired"]["color"] == "blue"
+ assert accepted["clientToken"] == "update-token"
+
+ mqtt_publish(publisher, f"$aws/things/{thing_name}/shadow/get", b'{"clientToken":"get-token"}')
+ topic, payload = mqtt_read_publish(subscriber)
+ assert topic == f"$aws/things/{thing_name}/shadow/get/accepted"
+ got = json.loads(payload)
+ assert got["state"]["desired"]["color"] == "blue"
+ assert got["clientToken"] == "get-token"
+
+ mqtt_publish(publisher, f"$aws/things/{thing_name}/shadow/delete", b'{"clientToken":"delete-token"}')
+ topic, payload = mqtt_read_publish(subscriber)
+ assert topic == f"$aws/things/{thing_name}/shadow/delete/accepted"
+ deleted = json.loads(payload)
+ assert deleted["state"]["desired"]["color"] == "blue"
+ assert deleted["clientToken"] == "delete-token"
+
+
+def mqtt_connect(client_id):
+ client = socket.create_connection(("floci", 1883), timeout=5)
+ client.settimeout(5)
+ body = mqtt_utf8("MQTT") + bytes([4, 2, 0, 60]) + mqtt_utf8(client_id)
+ client.sendall(bytes([0x10]) + mqtt_remaining_length(len(body)) + body)
+ assert mqtt_read_packet(client) == b"\x20\x02\x00\x00"
+ return client
+
+
+def mqtt5_connect(client_id):
+ client = socket.create_connection(("floci", 1883), timeout=5)
+ client.settimeout(5)
+ body = mqtt_utf8("MQTT") + bytes([5, 2, 0, 60, 0]) + mqtt_utf8(client_id)
+ client.sendall(bytes([0x10]) + mqtt_remaining_length(len(body)) + body)
+ mqtt_assert_v5_connack(mqtt_read_packet(client))
+ return client
+
+
+def mqtt_assert_v5_connack(packet):
+ assert packet[0] == 0x20
+ index = 1
+ while packet[index] & 0x80:
+ index += 1
+ index += 1
+ assert packet[index] == 0x00
+ assert packet[index + 1] == 0x00
+
+
+def mqtt_subscribe(client, topic):
+ body = b"\x00\x01" + mqtt_utf8(topic) + b"\x00"
+ client.sendall(bytes([0x82]) + mqtt_remaining_length(len(body)) + body)
+ assert mqtt_read_packet(client) == b"\x90\x03\x00\x01\x00"
+
+
+def mqtt_publish(client, topic, payload):
+ body = mqtt_utf8(topic) + payload
+ client.sendall(bytes([0x30]) + mqtt_remaining_length(len(body)) + body)
+
+
+def mqtt_read_publish(client):
+ packet = mqtt_read_packet(client)
+ assert packet[0] & 0xF0 == 0x30
+ index = 1
+ while packet[index] & 0x80:
+ index += 1
+ index += 1
+ topic_length = struct.unpack("!H", packet[index:index + 2])[0]
+ index += 2
+ topic = packet[index:index + topic_length].decode()
+ index += topic_length
+ return topic, packet[index:]
+
+
+def mqtt_read_packet(client):
+ first = client.recv(1)
+ assert first
+ remaining = 0
+ multiplier = 1
+ encoded_bytes = bytearray()
+ while True:
+ encoded = client.recv(1)
+ assert encoded
+ encoded_bytes.extend(encoded)
+ remaining += (encoded[0] & 127) * multiplier
+ multiplier *= 128
+ if encoded[0] & 128 == 0:
+ break
+ body = client.recv(remaining)
+ assert len(body) == remaining
+ return first + bytes(encoded_bytes) + body
+
+
+def mqtt_utf8(value):
+ encoded = value.encode()
+ return struct.pack("!H", len(encoded)) + encoded
+
+
+def mqtt_remaining_length(length):
+ encoded = bytearray()
+ value = length
+ while True:
+ byte = value % 128
+ value //= 128
+ if value:
+ byte |= 128
+ encoded.append(byte)
+ if not value:
+ return bytes(encoded)
diff --git a/docs/services/iot.md b/docs/services/iot.md
new file mode 100644
index 0000000000..0cf78d85b8
--- /dev/null
+++ b/docs/services/iot.md
@@ -0,0 +1,141 @@
+# AWS IoT Core
+
+Floci's IoT service emulates the AWS IoT Core control plane, IoT Data shadow APIs, and MQTT data-plane behavior used by local device and SDK tests.
+
+## MVP 1 Coverage
+
+Status: complete for the local emulator slice.
+
+Supported MVP 1 behavior:
+
+- Thing CRUD with idempotent identical `CreateThing`, duplicate-conflict semantics, `UpdateThing.expectedVersion`, and list pagination.
+- Certificate basics: `CreateKeysAndCertificate`, `CreateCertificateFromCsr`, `DescribeCertificate`, `ListCertificates`, `UpdateCertificate`, and `DeleteCertificate` with active/attached delete constraints.
+- Policy basics: `CreatePolicy`, `GetPolicy`, `ListPolicies`, `DeletePolicy`, policy version lifecycle, `AttachPolicy`, `DetachPolicy`, `ListAttachedPolicies`, and `ListTargetsForPolicy`.
+- Thing principal basics: `AttachThingPrincipal`, `DetachThingPrincipal`, `ListThingPrincipals`, and `ListPrincipalThings`.
+- Tags for things, certificates, policies, and topic rules.
+- IoT Data retained messages: retained `Publish`, `GetRetainedMessage`, and paginated `ListRetainedMessages`.
+- Shadow null-delete and version-conflict behavior for HTTP and shared service paths.
+- Topic rule duplicate/delete/replace semantics, plus `republish`, `sqs`, `sns`, `s3`, `dynamoDBv2`, `kinesis`, and `lambda` action dispatch.
+
+Current MVP 1 limitations:
+
+- Certificate CSR handling creates emulator-local certificates; it does not perform real CA signing.
+- MQTT auth remains permissive; certificate and policy resources are modeled for provisioning compatibility, not enforced as broker authorization yet.
+- Rules support basic topic filter extraction and action dispatch only; SQL projection, WHERE evaluation, substitutions, and error actions remain follow-up scope.
+
+## MVP 2 Coverage
+
+Status: implemented for the current SDK compatibility slice.
+
+Supported MVP 2 behavior:
+
+- Thing types: `CreateThingType`, `DescribeThingType`, `ListThingTypes`, `UpdateThingType`, `DeprecateThingType`, and `DeleteThingType` with typed `CreateThing` association and in-use delete protection.
+- 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.
+- 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`.
+- IoT rules can dispatch matching payloads to SQS, SNS, S3, DynamoDB v2, Kinesis, Lambda, and MQTT republish targets.
+
+Current MVP 2 limitations:
+
+- `DeleteConnection.preventWillMessage` is accepted for SDK request compatibility, but the embedded broker does not expose selective Last Will suppression.
+- HTTP IoT Data `Publish` still treats QoS and MQTT5 metadata as compatibility inputs only; those properties are not fully forwarded or persisted yet.
+- `SendDirectMessage` publishes to the requested MQTT topic through the embedded broker. Unlike AWS IoT Core, it does not yet bypass subscription matching to deliver to a client that is not subscribed to that topic.
+- `GetConnection` and `ListSubscriptions` report live in-memory broker state only; offline persistent session subscription reporting is not modeled yet.
+- 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.
+
+## MQTT Broker
+
+Status: complete.
+
+Floci uses Vert.x MQTT as the embedded MQTT protocol server. `IotMqttBrokerService` owns the broker lifecycle, live session registry, subscription registry, MQTT fan-out, and the bridge into IoT service behavior.
+
+Broker scope:
+
+- Target real AWS IoT/device SDK style MQTT clients, not only handcrafted packet tests.
+- Support MQTT v3 and MQTT 5 CONNECT handling used by local compatibility tests.
+- Support QoS 0 and QoS 1 publish/subscribe behavior for the local AWS IoT slice.
+- Keep MQTT plaintext-only for this phase; TLS and mTLS are out of scope.
+- Keep MQTT authorization permissive for now, but leave room for a later pluggable IoT certificate and policy authorizer.
+- Keep MQTT broker logging minimal.
+- Validate the relevant IoT compatibility tests against the native binary before considering the phase complete.
+
+## Reserved Topics
+
+AWS IoT reserved topics such as `$aws/things/{thingName}/shadow/update` are service control topics, not ordinary application topics. Floci should handle these publishes by invoking IoT shadow behavior and then publishing the AWS-compatible response topics through the broker.
+
+Required phase 7 reserved-topic behavior:
+
+- Classic unnamed shadows: `$aws/things/{thingName}/shadow/update`, `get`, and `delete`.
+- Named shadows: `$aws/things/{thingName}/shadow/name/{shadowName}/update`, `get`, and `delete`.
+- Shadow response topics: `accepted`, `rejected`, `documents`, and `delta` where applicable.
+- Basic Ingest and Jobs topic families are desired follow-up scope, but should not block restoring the broker unless explicitly pulled into the implementation phase.
+
+Reserved request topics are handled by Floci before normal MQTT fan-out. The original `$aws/...` request publish is not routed as an application message; generated accepted, rejected, documents, and delta responses are published back through `IotMqttBrokerService.publish(...)` so matching MQTT subscribers receive broker-native messages.
+
+Implementation notes:
+
+- Vert.x MQTT handles the wire protocol and connection lifecycle.
+- Floci-owned session, subscription, and retained-message state drives local AWS IoT compatibility behavior.
+- Normal client publishes call `IotService.publish(...)` so retained-message storage, event recording, and rule evaluation remain service-owned.
+- Internal broker publishes fan out only to MQTT subscribers and do not recursively evaluate IoT topic rules.
+
+Current accepted limitation:
+
+- Certificate and policy authorization are not enforced at the broker layer yet.
+- Persistent offline sessions are not modeled yet.
+- QoS 2 and advanced MQTT 5 property semantics remain follow-up scope.
+
+## Implementation Shape
+
+The MQTT integration should keep service behavior separated from broker mechanics:
+
+- `IotMqttBrokerService` owns Vert.x MQTT lifecycle and broker-native publish helpers.
+- The broker publish handler detects AWS IoT reserved topics.
+- IoT reserved-topic handling lives in IoT service code or a focused reserved-topic handler, not in packet parsing code.
+- AWS-generated shadow responses are published back through `IotMqttBrokerService.publish(...)` so regular MQTT subscribers receive broker-native messages.
+
+## Phase 7 Completion Criteria
+
+Phase 7 completion criteria:
+
+- Vert.x MQTT is the active MQTT broker implementation.
+- Reserved shadow topics are handled from the broker publish handler.
+- AWS-generated shadow responses are published through the broker service, not by manually writing MQTT packets.
+- MQTT 5 CONNECT and publish/subscribe behavior are covered by automated tests.
+- Classic unnamed shadow MQTT topics are covered by automated tests.
+- Named shadow MQTT topics are covered by automated tests.
+- Relevant IoT compatibility tests pass against the native binary.
+
+## Rules Engine
+
+Status: complete for the MVP 2 action slice.
+
+Phase 8 adds stored IoT topic rules and dispatches matching IoT publishes to rule actions.
+
+Supported rule behavior:
+
+- `CreateTopicRule`, `GetTopicRule`, `ListTopicRules`, `EnableTopicRule`, `DisableTopicRule`, and `DeleteTopicRule` through AWS SDK-compatible IoT control-plane paths.
+- SQL topic filter extraction for rules shaped like `SELECT * FROM 'topic/filter'`.
+- MQTT-style topic filter matching for exact topics, `+`, and terminal `#`.
+- IoT Data `Publish` and MQTT publishes use the same rule dispatch path.
+- `republish` action republishes the original payload to another MQTT topic through `IotMqttBrokerService`.
+- `sqs` action sends the original payload to an SQS queue through Floci's SQS service boundary.
+- `sns` action publishes the original payload to an SNS topic through Floci's SNS service boundary.
+- `s3` action writes the original payload to the configured bucket/key through Floci's S3 service boundary.
+- `dynamoDBv2` action writes JSON object payload fields as DynamoDB attribute values through Floci's DynamoDB service boundary.
+- `kinesis` action puts the original payload into a Kinesis stream through Floci's Kinesis service boundary.
+- `lambda` action invokes the configured function ARN through Floci's Lambda service boundary.
+
+Current limitations:
+
+- SQL projection, WHERE clauses, functions, substitutions, error actions, and less common AWS IoT rule action types are follow-up scope.
+
+Open follow-up scope for phase 7 unless explicitly deferred:
+
+- Basic Ingest topics under `$aws/rules/...`.
+- AWS IoT Jobs reserved topics and required job lifecycle behavior.
diff --git a/mkdocs.yml b/mkdocs.yml
index c1540c4d9b..920885db5e 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -124,6 +124,7 @@ nav:
- CloudFront: services/cloudfront.md
- Route53: services/route53.md
- AWS Cloud Map: services/cloudmap.md
+ - AWS IoT Core: services/iot.md
- AppSync: services/appsync.md
- Transfer Family: services/transfer.md
- AWS Config: services/config.md
diff --git a/pom.xml b/pom.xml
index fd296299b7..2c01e45b87 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,6 +43,11 @@
<artifactId>proto-google-common-protos</artifactId>
<version>2.49.0</version>
</dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2-mvstore</artifactId>
+ <version>2.3.232</version>
+ </dependency>
</dependencies>
</dependencyManagement>
@@ -92,6 +97,10 @@
<groupId>io.quarkus</groupId>
<artifactId>quarkus-vertx</artifactId>
</dependency>
+ <dependency>
+ <groupId>io.vertx</groupId>
+ <artifactId>vertx-mqtt</artifactId>
+ </dependency>
<!-- cron-utils for EventBridge schedule expression parsing -->
<dependency>
@@ -232,6 +241,18 @@
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.paho</groupId>
+ <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
+ <version>1.2.5</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.paho</groupId>
+ <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
+ <version>1.2.5</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index a6b2f0f9e7..584f51ac5e 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -458,6 +458,34 @@ public interface EmulatorConfig {
BatchServiceConfig batch();
UiServiceConfig ui();
S3VectorsServiceConfig s3vectors();
+ IotServiceConfig iot();
+ IotDataServiceConfig iotdata();
+ }
+
+ interface IotServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ MqttConfig mqtt();
+ }
+
+ interface MqttConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ @WithDefault("false")
+ boolean autoStart();
+
+ @WithDefault("0.0.0.0")
+ String host();
+
+ @WithDefault("1883")
+ int port();
+ }
+
+ interface IotDataServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
}
interface CloudTrailServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 2b0e271ff1..bc35218c7f 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeControll
import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;
import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
import io.github.hectorvent.floci.services.eks.EksController;
+import io.github.hectorvent.floci.services.iot.IotController;
+import io.github.hectorvent.floci.services.iot.IotDataController;
import io.github.hectorvent.floci.services.pipes.PipesController;
import io.github.hectorvent.floci.services.lambda.LambdaController;
import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
@@ -347,7 +349,15 @@ public class ResolvedServiceCatalog {
"s3vectors", storageMode(config.storage().services().s3vectors().mode(), config.storage().mode()),
config.storage().services().s3vectors().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
- Set.of(), Set.of("s3vectors"), Set.of(), Set.of(S3VectorsController.class))
+ Set.of(), Set.of("s3vectors"), Set.of(), Set.of(S3VectorsController.class)),
+ descriptor("iot", "iot", config.services().iot().enabled(), true,
+ "iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("iot", "execute-api"), Set.of(), Set.of(IotController.class)),
+ descriptor("iotdata", "iotdata", config.services().iotdata().enabled(), true,
+ "iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("iotdata"), Set.of(), Set.of(IotDataController.class))
));
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java
index de7159ef7f..4ccd4617b7 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java
@@ -54,6 +54,12 @@ public class ServiceEnabledFilter implements ContainerRequestFilter {
.orElse(null);
}
+ var resourceMatch = catalog.byResourceClass(resourceClass());
+ if (resourceMatch.isPresent()) {
+ ServiceDescriptor descriptor = resourceMatch.get();
+ return new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol());
+ }
+
String auth = ctx.getHeaderString("Authorization");
if (auth != null) {
Matcher m = AUTH_SERVICE_PATTERN.matcher(auth);
@@ -66,9 +72,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter {
}
}
- return catalog.byResourceClass(resourceClass())
- .map(descriptor -> new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol()))
- .orElse(null);
+ return null;
}
private Class<?> resourceClass() {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
index 71ac56a59a..2cae0993cf 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
@@ -14,6 +14,7 @@ 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;
@@ -63,8 +64,18 @@ public class SharedTagsController {
}
@GET
- @Path("/{arn: .*}")
+ public Response listTagsByQuery(@Context HttpHeaders headers,
+ @QueryParam("resourceArn") String arn) {
+ return listTagsForArn(headers, arn);
+ }
+
+ @GET
+ @Path("/{arn: .+}")
public Response listTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
+ return listTagsForArn(headers, arn);
+ }
+
+ private Response listTagsForArn(HttpHeaders headers, String arn) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
Map<String, String> tags = handler.listTags(region, arn);
@@ -72,7 +83,15 @@ public class SharedTagsController {
}
@POST
- @Path("/{arn: .*}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response tagResourceByBody(@Context HttpHeaders headers, String body) {
+ String arn = readResourceArn(body);
+ TagHandler handler = resolveHandler(arn);
+ return doTagResource(headers, handler, arn, body, Response.ok(objectMapper.createObjectNode()).build());
+ }
+
+ @POST
+ @Path("/{arn: .+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response tagResourcePost(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@@ -82,11 +101,11 @@ public class SharedTagsController {
throw new AwsException("MethodNotAllowedException",
"POST is not supported for " + handler.serviceKey() + " tag resources; use PUT.", 405);
}
- return doTagResource(headers, handler, arn, body);
+ return doTagResource(headers, handler, arn, body, Response.noContent().build());
}
@PUT
- @Path("/{arn: .*}")
+ @Path("/{arn: .+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response tagResourcePut(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@@ -96,17 +115,17 @@ public class SharedTagsController {
throw new AwsException("MethodNotAllowedException",
"PUT is not supported for " + handler.serviceKey() + " tag resources; use POST.", 405);
}
- return doTagResource(headers, handler, arn, body);
+ return doTagResource(headers, handler, arn, body, Response.noContent().build());
}
- private Response doTagResource(HttpHeaders headers, TagHandler handler, String arn, String body) {
+ private Response doTagResource(HttpHeaders headers, TagHandler handler, String arn, String body, Response successResponse) {
String region = regionResolver.resolveRegion(headers);
String effectiveBody = (body == null || body.isBlank()) ? "{}" : body;
try {
JsonNode node = objectMapper.readTree(effectiveBody);
Map<String, String> tags = parseTags(handler, node);
handler.tagResource(region, arn, tags);
- return Response.noContent().build();
+ return successResponse;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
@@ -116,15 +135,26 @@ public class SharedTagsController {
}
@DELETE
- @Path("/{arn: .*}")
+ public Response untagResourceByQuery(@Context HttpHeaders headers,
+ @Context UriInfo uriInfo,
+ @QueryParam("resourceArn") String arn) {
+ return untagResourceForArn(headers, uriInfo, arn, Response.ok(objectMapper.createObjectNode()).build());
+ }
+
+ @DELETE
+ @Path("/{arn: .+}")
public Response untagResource(@Context HttpHeaders headers,
- @Context UriInfo uriInfo,
- @PathParam("arn") String arn) {
+ @Context UriInfo uriInfo,
+ @PathParam("arn") String arn) {
+ return untagResourceForArn(headers, uriInfo, arn, Response.noContent().build());
+ }
+
+ private Response untagResourceForArn(HttpHeaders headers, UriInfo uriInfo, String arn, Response successResponse) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
List<String> tagKeys = readTagKeys(handler, uriInfo);
handler.untagResource(region, arn, tagKeys);
- return Response.noContent().build();
+ return successResponse;
}
private ObjectNode buildListResponse(TagHandler handler, Map<String, String> tags) {
@@ -202,6 +232,15 @@ public class SharedTagsController {
return (values == null) ? List.of() : List.copyOf(values);
}
+ private String readResourceArn(String body) {
+ try {
+ JsonNode node = objectMapper.readTree((body == null || body.isBlank()) ? "{}" : body);
+ return node.path("resourceArn").asText(null);
+ } catch (Exception e) {
+ throw new AwsException("BadRequestException", e.getMessage(), 400);
+ }
+ }
+
private TagHandler resolveHandler(String arn) {
// arn:aws:<service>:<region>:<account>:<resource>
String[] parts = arn.split(":", 6);
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
new file mode 100644
index 0000000000..34987ae3da
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
@@ -0,0 +1,1153 @@
+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.IotCertificate;
+import io.github.hectorvent.floci.services.iot.model.IotJob;
+import io.github.hectorvent.floci.services.iot.model.IotJobExecution;
+import io.github.hectorvent.floci.services.iot.model.IotPolicy;
+import io.github.hectorvent.floci.services.iot.model.IotThingGroup;
+import io.github.hectorvent.floci.services.iot.model.IotThingType;
+import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
+import io.github.hectorvent.floci.services.iot.model.Thing;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.PATCH;
+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;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class IotController {
+
+ private final IotService iotService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public IotController(IotService iotService, RegionResolver regionResolver, ObjectMapper objectMapper) {
+ this.iotService = iotService;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ }
+
+ @GET
+ @Path("/endpoint")
+ public Response describeEndpoint(@QueryParam("endpointType") String endpointType) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("endpointAddress", iotService.describeEndpoint(endpointType));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/things/{thingName}")
+ public Response createThing(@PathParam("thingName") String thingName,
+ @Context HttpHeaders headers,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ Thing thing = iotService.createThing(thingName, parseAttributes(body), parseThingTypeName(body), region);
+ return Response.ok(buildThingResponse(thing)).build();
+ }
+
+ @GET
+ @Path("/things/{thingName}")
+ public Response describeThing(@PathParam("thingName") String thingName,
+ @Context HttpHeaders headers) {
+ String region = regionResolver.resolveRegion(headers);
+ return Response.ok(buildThingResponse(iotService.describeThing(thingName, region))).build();
+ }
+
+ @GET
+ @Path("/things")
+ public Response listThings(@Context HttpHeaders headers,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ String region = regionResolver.resolveRegion(headers);
+ IotService.Page<Thing> page = iotService.listThings(region, maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode things = response.putArray("things");
+ for (Thing thing : page.items()) {
+ ObjectNode summary = objectMapper.createObjectNode();
+ summary.put("thingName", thing.getThingName());
+ summary.put("thingArn", thing.getThingArn());
+ things.add(summary);
+ }
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @PATCH
+ @Path("/things/{thingName}")
+ public Response updateThing(@PathParam("thingName") String thingName,
+ @Context HttpHeaders headers,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ Thing thing = iotService.updateThing(thingName, parseAttributes(body), parseExpectedVersion(body), region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingName", thing.getThingName());
+ response.put("thingArn", thing.getThingArn());
+ response.put("version", thing.getVersion());
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/things/{thingName}")
+ public Response deleteThing(@PathParam("thingName") String thingName,
+ @Context HttpHeaders headers) {
+ String region = regionResolver.resolveRegion(headers);
+ iotService.deleteThing(thingName, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/untag")
+ public Response untagResource(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ iotService.untagResource(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);
+ }
+ }
+
+ @POST
+ @Path("/keys-and-certificate")
+ @Consumes(MediaType.WILDCARD)
+ public Response createKeysAndCertificate(@Context HttpHeaders headers,
+ @QueryParam("setAsActive") boolean setAsActive) {
+ IotCertificate certificate = iotService.createKeysAndCertificate(setAsActive, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("certificateArn", certificate.getCertificateArn());
+ response.put("certificateId", certificate.getCertificateId());
+ response.put("certificatePem", certificate.getCertificatePem());
+ ObjectNode keyPair = response.putObject("keyPair");
+ keyPair.put("PublicKey", certificate.getPublicKey());
+ keyPair.put("PrivateKey", certificate.getPrivateKey());
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/certificates")
+ public Response createCertificateFromCsr(@Context HttpHeaders headers,
+ @QueryParam("setAsActive") boolean setAsActive,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ IotCertificate certificate = iotService.createCertificateFromCsr(
+ request.path("certificateSigningRequest").asText(null), setAsActive, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("certificateArn", certificate.getCertificateArn());
+ response.put("certificateId", certificate.getCertificateId());
+ response.put("certificatePem", certificate.getCertificatePem());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/certificates/{certificateId}")
+ public Response describeCertificate(@Context HttpHeaders headers,
+ @PathParam("certificateId") String certificateId) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("certificateDescription", buildCertificateDescription(
+ iotService.describeCertificate(certificateId, regionResolver.resolveRegion(headers))));
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/certificates")
+ public Response listCertificates(@Context HttpHeaders headers) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode certificates = response.putArray("certificates");
+ for (IotCertificate certificate : iotService.listCertificates(regionResolver.resolveRegion(headers))) {
+ ObjectNode item = certificates.addObject();
+ item.put("certificateArn", certificate.getCertificateArn());
+ item.put("certificateId", certificate.getCertificateId());
+ item.put("status", certificate.getStatus());
+ putEpoch(item, "creationDate", certificate.getCreationDate());
+ }
+ return Response.ok(response).build();
+ }
+
+ @PUT
+ @Path("/certificates/{certificateId}")
+ public Response updateCertificate(@Context HttpHeaders headers,
+ @PathParam("certificateId") String certificateId,
+ @QueryParam("newStatus") String newStatus,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ String status = newStatus != null ? newStatus
+ : request.hasNonNull("newStatus") ? request.path("newStatus").asText()
+ : request.path("status").asText();
+ iotService.updateCertificate(certificateId, status, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @DELETE
+ @Path("/certificates/{certificateId}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteCertificate(@Context HttpHeaders headers,
+ @PathParam("certificateId") String certificateId) {
+ iotService.deleteCertificate(certificateId, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/policies/{policyName}")
+ public Response createPolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ IotPolicy policy = iotService.createPolicy(policyName, request.path("policyDocument").asText(), regionResolver.resolveRegion(headers));
+ return Response.ok(buildPolicyResponse(policy)).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/policies/{policyName}")
+ public Response getPolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName) {
+ return Response.ok(buildPolicyResponse(iotService.getPolicy(policyName, regionResolver.resolveRegion(headers)))).build();
+ }
+
+ @GET
+ @Path("/policies")
+ public Response listPolicies(@Context HttpHeaders headers) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode policies = response.putArray("policies");
+ for (IotPolicy policy : iotService.listPolicies(regionResolver.resolveRegion(headers))) {
+ ObjectNode item = policies.addObject();
+ item.put("policyName", policy.getPolicyName());
+ item.put("policyArn", policy.getPolicyArn());
+ }
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/policies/{policyName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deletePolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName) {
+ iotService.deletePolicy(policyName, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/policies/{policyName}/version")
+ public Response createPolicyVersion(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @QueryParam("setAsDefault") boolean setAsDefault,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ IotPolicy policy = iotService.getPolicy(policyName, regionResolver.resolveRegion(headers));
+ IotPolicy.PolicyVersion version = iotService.createPolicyVersion(policyName,
+ request.path("policyDocument").asText(), setAsDefault, regionResolver.resolveRegion(headers));
+ return Response.ok(buildPolicyVersionResponse(policy, version, setAsDefault)).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/policies/{policyName}/version")
+ public Response listPolicyVersions(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName) {
+ String region = regionResolver.resolveRegion(headers);
+ IotPolicy policy = iotService.getPolicy(policyName, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode versions = response.putArray("policyVersions");
+ for (IotPolicy.PolicyVersion version : iotService.listPolicyVersions(policyName, region)) {
+ versions.add(buildPolicyVersionSummary(policy, version));
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/policies/{policyName}/version/{policyVersionId}")
+ public Response getPolicyVersion(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @PathParam("policyVersionId") String policyVersionId) {
+ String region = regionResolver.resolveRegion(headers);
+ IotPolicy policy = iotService.getPolicy(policyName, region);
+ IotPolicy.PolicyVersion version = iotService.getPolicyVersion(policyName, policyVersionId, region);
+ return Response.ok(buildPolicyVersionResponse(policy, version, version.getVersionId().equals(policy.getDefaultVersionId()))).build();
+ }
+
+ @PATCH
+ @Path("/policies/{policyName}/version/{policyVersionId}")
+ @Consumes(MediaType.WILDCARD)
+ public Response setDefaultPolicyVersion(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @PathParam("policyVersionId") String policyVersionId) {
+ iotService.setDefaultPolicyVersion(policyName, policyVersionId, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @DELETE
+ @Path("/policies/{policyName}/version/{policyVersionId}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deletePolicyVersion(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @PathParam("policyVersionId") String policyVersionId) {
+ iotService.deletePolicyVersion(policyName, policyVersionId, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @PUT
+ @Path("/target-policies/{policyName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response attachPolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @QueryParam("target") String target,
+ String body) {
+ iotService.attachPolicy(policyName, parseTarget(target, body), regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/target-policies/{policyName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response detachPolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName,
+ @QueryParam("target") String target,
+ String body) {
+ iotService.detachPolicy(policyName, parseTarget(target, body), regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @GET
+ @Path("/attached-policies/{target: .+}")
+ public Response listAttachedPolicies(@Context HttpHeaders headers,
+ @PathParam("target") String target) {
+ return listAttachedPoliciesResponse(headers, target);
+ }
+
+ @POST
+ @Path("/attached-policies/{target: .+}")
+ @Consumes(MediaType.WILDCARD)
+ public Response listAttachedPoliciesPost(@Context HttpHeaders headers,
+ @PathParam("target") String target) {
+ return listAttachedPoliciesResponse(headers, target);
+ }
+
+ private Response listAttachedPoliciesResponse(HttpHeaders headers, String target) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode policies = response.putArray("policies");
+ for (IotPolicy policy : iotService.listAttachedPolicies(target, regionResolver.resolveRegion(headers))) {
+ ObjectNode item = policies.addObject();
+ item.put("policyName", policy.getPolicyName());
+ item.put("policyArn", policy.getPolicyArn());
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/policy-targets/{policyName}")
+ public Response listTargetsForPolicy(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName) {
+ return listTargetsForPolicyResponse(headers, policyName);
+ }
+
+ @POST
+ @Path("/policy-targets/{policyName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response listTargetsForPolicyPost(@Context HttpHeaders headers,
+ @PathParam("policyName") String policyName) {
+ return listTargetsForPolicyResponse(headers, policyName);
+ }
+
+ private Response listTargetsForPolicyResponse(HttpHeaders headers, String policyName) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode targets = response.putArray("targets");
+ iotService.listTargetsForPolicy(policyName, regionResolver.resolveRegion(headers)).forEach(targets::add);
+ return Response.ok(response).build();
+ }
+
+ @PUT
+ @Path("/things/{thingName}/principals")
+ @Consumes(MediaType.WILDCARD)
+ public Response attachThingPrincipal(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @HeaderParam("x-amzn-principal") String principalHeader,
+ @QueryParam("principal") String principal) {
+ iotService.attachThingPrincipal(thingName, principalHeader != null ? principalHeader : principal, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @DELETE
+ @Path("/things/{thingName}/principals")
+ @Consumes(MediaType.WILDCARD)
+ public Response detachThingPrincipal(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @HeaderParam("x-amzn-principal") String principalHeader,
+ @QueryParam("principal") String principal) {
+ iotService.detachThingPrincipal(thingName, principalHeader != null ? principalHeader : principal, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @GET
+ @Path("/things/{thingName}/principals")
+ public Response listThingPrincipals(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode principals = response.putArray("principals");
+ iotService.listThingPrincipals(thingName, regionResolver.resolveRegion(headers)).forEach(principals::add);
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/principals/things")
+ public Response listPrincipalThings(@Context HttpHeaders headers,
+ @HeaderParam("x-amzn-principal") String principalHeader,
+ @QueryParam("principal") String principal) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode things = response.putArray("things");
+ iotService.listPrincipalThings(principalHeader != null ? principalHeader : principal, regionResolver.resolveRegion(headers)).forEach(things::add);
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/thing-types/{thingTypeName}")
+ public Response createThingType(@Context HttpHeaders headers,
+ @PathParam("thingTypeName") String thingTypeName,
+ String body) {
+ IotThingType type = iotService.createThingType(thingTypeName, parseProperties(body, "thingTypeProperties"), regionResolver.resolveRegion(headers));
+ return Response.ok(buildThingTypeCreateResponse(type)).build();
+ }
+
+ @GET
+ @Path("/thing-types/{thingTypeName}")
+ public Response describeThingType(@Context HttpHeaders headers,
+ @PathParam("thingTypeName") String thingTypeName) {
+ return Response.ok(buildThingTypeDescription(iotService.describeThingType(thingTypeName, regionResolver.resolveRegion(headers)))).build();
+ }
+
+ @GET
+ @Path("/thing-types")
+ public Response listThingTypes(@Context HttpHeaders headers,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<IotThingType> page = iotService.listThingTypes(regionResolver.resolveRegion(headers), maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode types = response.putArray("thingTypes");
+ page.items().forEach(type -> types.add(buildThingTypeSummary(type)));
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @PATCH
+ @Path("/thing-types/{thingTypeName}")
+ public Response updateThingType(@Context HttpHeaders headers,
+ @PathParam("thingTypeName") String thingTypeName,
+ String body) {
+ iotService.updateThingType(thingTypeName, parseProperties(body, "thingTypeProperties"), regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/thing-types/{thingTypeName}/deprecate")
+ @Consumes(MediaType.WILDCARD)
+ public Response deprecateThingType(@Context HttpHeaders headers,
+ @PathParam("thingTypeName") String thingTypeName) {
+ iotService.deprecateThingType(thingTypeName, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @DELETE
+ @Path("/thing-types/{thingTypeName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteThingType(@Context HttpHeaders headers,
+ @PathParam("thingTypeName") String thingTypeName) {
+ iotService.deleteThingType(thingTypeName, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/thing-groups/{thingGroupName}")
+ public Response createThingGroup(@Context HttpHeaders headers,
+ @PathParam("thingGroupName") String thingGroupName,
+ String body) {
+ IotThingGroup group = iotService.createThingGroup(thingGroupName, parseProperties(body, "thingGroupProperties"), regionResolver.resolveRegion(headers));
+ return Response.ok(buildThingGroupCreateResponse(group)).build();
+ }
+
+ @GET
+ @Path("/thing-groups/{thingGroupName}")
+ public Response describeThingGroup(@Context HttpHeaders headers,
+ @PathParam("thingGroupName") String thingGroupName) {
+ return Response.ok(buildThingGroupDescription(iotService.describeThingGroup(thingGroupName, regionResolver.resolveRegion(headers)))).build();
+ }
+
+ @GET
+ @Path("/thing-groups")
+ public Response listThingGroups(@Context HttpHeaders headers,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<IotThingGroup> page = iotService.listThingGroups(regionResolver.resolveRegion(headers), maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode groups = response.putArray("thingGroups");
+ page.items().forEach(group -> groups.add(buildThingGroupSummary(group)));
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @PATCH
+ @Path("/thing-groups/{thingGroupName}")
+ public Response updateThingGroup(@Context HttpHeaders headers,
+ @PathParam("thingGroupName") String thingGroupName,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ Long expectedVersion = request.hasNonNull("expectedVersion") ? request.path("expectedVersion").asLong() : null;
+ IotThingGroup group = iotService.updateThingGroup(thingGroupName, request.path("thingGroupProperties"), expectedVersion,
+ regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("version", group.getVersion());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @DELETE
+ @Path("/thing-groups/{thingGroupName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteThingGroup(@Context HttpHeaders headers,
+ @PathParam("thingGroupName") String thingGroupName) {
+ iotService.deleteThingGroup(thingGroupName, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @PUT
+ @Path("/thing-groups/addThingToThingGroup")
+ public Response addThingToThingGroup(@Context HttpHeaders headers,
+ String body) {
+ GroupMembershipRequest request = parseGroupMembershipRequest(body);
+ iotService.addThingToThingGroup(request.thingGroupName(), request.thingName(), regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @PUT
+ @Path("/thing-groups/removeThingFromThingGroup")
+ public Response removeThingFromThingGroup(@Context HttpHeaders headers,
+ String body) {
+ GroupMembershipRequest request = parseGroupMembershipRequest(body);
+ iotService.removeThingFromThingGroup(request.thingGroupName(), request.thingName(), regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @GET
+ @Path("/thing-groups/{thingGroupName}/things")
+ public Response listThingsInThingGroup(@Context HttpHeaders headers,
+ @PathParam("thingGroupName") String thingGroupName) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode things = response.putArray("things");
+ iotService.listThingsInThingGroup(thingGroupName, regionResolver.resolveRegion(headers)).forEach(things::add);
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/things/{thingName}/thing-groups")
+ public Response listThingGroupsForThing(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode groups = response.putArray("thingGroups");
+ iotService.listThingGroupsForThing(thingName, regionResolver.resolveRegion(headers)).forEach(group -> groups.add(buildThingGroupSummary(group)));
+ return Response.ok(response).build();
+ }
+
+ @PUT
+ @Path("/jobs/{jobId}")
+ public Response createJob(@Context HttpHeaders headers,
+ @PathParam("jobId") String jobId,
+ String body) {
+ try {
+ IotJob job = iotService.createJob(jobId, objectMapper.readTree(body == null || body.isBlank() ? "{}" : body),
+ regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("jobArn", job.getJobArn());
+ response.put("jobId", job.getJobId());
+ response.put("description", job.getDescription());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/jobs/{jobId}")
+ public Response describeJob(@Context HttpHeaders headers,
+ @PathParam("jobId") String jobId) {
+ IotJob job = iotService.describeJob(jobId, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ if (job.getDocumentSource() != null) {
+ response.put("documentSource", job.getDocumentSource());
+ }
+ response.set("job", buildJobResponse(job));
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/jobs")
+ public Response listJobs(@Context HttpHeaders headers,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<IotJob> page = iotService.listJobs(regionResolver.resolveRegion(headers), maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode jobs = response.putArray("jobs");
+ page.items().forEach(job -> jobs.add(buildJobSummary(job)));
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/things/{thingName}/jobs")
+ public Response listJobExecutionsForThing(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<IotJobExecution> page = iotService.listJobExecutionsForThing(thingName,
+ regionResolver.resolveRegion(headers), maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode executionSummaries = response.putArray("executionSummaries");
+ ArrayNode queuedJobs = response.putArray("queuedJobs");
+ ArrayNode inProgressJobs = response.putArray("inProgressJobs");
+ page.items().forEach(execution -> {
+ ObjectNode controlSummary = executionSummaries.addObject();
+ controlSummary.put("jobId", execution.getJobId());
+ controlSummary.set("jobExecutionSummary", buildJobExecutionSummary(execution));
+ if ("IN_PROGRESS".equals(execution.getStatus())) {
+ inProgressJobs.add(buildJobsDataExecutionSummary(execution));
+ } else if ("QUEUED".equals(execution.getStatus())) {
+ queuedJobs.add(buildJobsDataExecutionSummary(execution));
+ }
+ });
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/things/{thingName}/jobs/{jobId}")
+ public Response describeJobExecution(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @PathParam("jobId") String jobId) {
+ String region = regionResolver.resolveRegion(headers);
+ IotJobExecution execution = iotService.describeJobExecution(thingName, jobId, region);
+ return Response.ok(jobExecutionResponse(execution, iotService.describeJob(jobId, region), true)).build();
+ }
+
+ @PUT
+ @Path("/things/{thingName}/jobs/{jobId}")
+ public Response startNextPendingJobExecution(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @PathParam("jobId") String jobId,
+ String body) {
+ if (!"$next".equals(jobId)) {
+ throw new AwsException("InvalidRequestException", "Unsupported job execution PUT path: " + jobId, 400);
+ }
+ String region = regionResolver.resolveRegion(headers);
+ IotJobExecution execution = iotService.startNextPendingJobExecution(thingName, parseStatusDetails(body), region);
+ return Response.ok(jobExecutionResponse(execution, iotService.describeJob(execution.getJobId(), region), true)).build();
+ }
+
+ @POST
+ @Path("/things/{thingName}/jobs/{jobId}")
+ public Response updateJobExecution(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @PathParam("jobId") String jobId,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ Long expectedVersion = request.hasNonNull("expectedVersion") ? request.path("expectedVersion").asLong() : null;
+ String region = regionResolver.resolveRegion(headers);
+ IotJobExecution execution = iotService.updateJobExecution(thingName, jobId, request.path("status").asText(null),
+ parseStatusDetails(request.path("statusDetails")), expectedVersion, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ if (request.path("includeJobExecutionState").asBoolean(false)) {
+ ObjectNode state = response.putObject("executionState");
+ state.put("status", execution.getStatus());
+ state.put("versionNumber", execution.getVersionNumber());
+ state.set("statusDetails", objectMapper.valueToTree(execution.getStatusDetails()));
+ }
+ if (request.path("includeJobDocument").asBoolean(false)) {
+ response.put("jobDocument", iotService.describeJob(jobId, region).getDocument());
+ }
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @PUT
+ @Path("/rules/{ruleName}")
+ public Response createTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName,
+ String body) {
+ return createTopicRuleResponse(headers, ruleName, body);
+ }
+
+ @POST
+ @Path("/rules/{ruleName}")
+ public Response createTopicRulePost(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName,
+ String body) {
+ return createTopicRuleResponse(headers, ruleName, body);
+ }
+
+ @PATCH
+ @Path("/rules/{ruleName}")
+ public Response replaceTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ JsonNode payload = request.has("topicRulePayload") ? request.path("topicRulePayload") : request;
+ IotTopicRule rule = iotService.replaceTopicRule(ruleName, payload, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ruleArn", rule.getRuleArn());
+ response.put("ruleName", rule.getRuleName());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private Response createTopicRuleResponse(HttpHeaders headers, String ruleName, String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ JsonNode payload = request.has("topicRulePayload") ? request.path("topicRulePayload") : request;
+ IotTopicRule rule = iotService.createTopicRule(ruleName, payload, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ruleArn", rule.getRuleArn());
+ response.put("ruleName", rule.getRuleName());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/rules/{ruleName}")
+ public Response getTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName) {
+ IotTopicRule rule = iotService.getTopicRule(ruleName, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ruleArn", rule.getRuleArn());
+ response.set("rule", buildTopicRuleResponse(rule));
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/rules")
+ public Response listTopicRules(@Context HttpHeaders headers) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode rules = response.putArray("rules");
+ for (IotTopicRule rule : iotService.listTopicRules(regionResolver.resolveRegion(headers))) {
+ ObjectNode item = rules.addObject();
+ item.put("ruleArn", rule.getRuleArn());
+ item.put("ruleName", rule.getRuleName());
+ item.put("topicPattern", topicPattern(rule.getSql()));
+ item.put("ruleDisabled", rule.isRuleDisabled());
+ putEpoch(item, "createdAt", rule.getCreatedAt());
+ }
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/rules/{ruleName}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName) {
+ iotService.deleteTopicRule(ruleName, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/rules/{ruleName}/enable")
+ @Consumes(MediaType.WILDCARD)
+ public Response enableTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName) {
+ iotService.setTopicRuleEnabled(ruleName, true, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/rules/{ruleName}/disable")
+ @Consumes(MediaType.WILDCARD)
+ public Response disableTopicRule(@Context HttpHeaders headers,
+ @PathParam("ruleName") String ruleName) {
+ iotService.setTopicRuleEnabled(ruleName, false, regionResolver.resolveRegion(headers));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Map<String, String> parseAttributes(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ JsonNode attributesNode = request.get("attributePayload");
+ if (attributesNode == null || !attributesNode.has("attributes")) {
+ attributesNode = request.get("AttributePayload");
+ }
+ if (attributesNode != null && attributesNode.has("attributes")) {
+ attributesNode = attributesNode.get("attributes");
+ } else if (attributesNode != null && attributesNode.has("Attributes")) {
+ attributesNode = attributesNode.get("Attributes");
+ }
+ Map<String, String> attributes = new HashMap<>();
+ if (attributesNode != null && attributesNode.isObject()) {
+ attributesNode.fields().forEachRemaining(entry -> attributes.put(entry.getKey(), entry.getValue().asText()));
+ }
+ return attributes;
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private Long parseExpectedVersion(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return request.hasNonNull("expectedVersion") ? request.path("expectedVersion").asLong() : null;
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private String parseThingTypeName(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return request.path("thingTypeName").asText(null);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private JsonNode parseProperties(String body, String field) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return request.path(field);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private GroupMembershipRequest parseGroupMembershipRequest(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return new GroupMembershipRequest(request.path("thingGroupName").asText(null), request.path("thingName").asText(null));
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private List<String> parseTagKeys(JsonNode tagKeysNode) {
+ List<String> tagKeys = new ArrayList<>();
+ if (tagKeysNode != null && tagKeysNode.isArray()) {
+ tagKeysNode.forEach(tagKey -> tagKeys.add(tagKey.asText()));
+ }
+ return tagKeys;
+ }
+
+ private String parseTarget(String queryTarget, String body) {
+ if (queryTarget != null && !queryTarget.isBlank()) {
+ return queryTarget;
+ }
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return request.path("target").asText(null);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private Map<String, String> parseStatusDetails(String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return parseStatusDetails(request.path("statusDetails"));
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private Map<String, String> parseStatusDetails(JsonNode node) {
+ Map<String, String> details = new HashMap<>();
+ if (node != null && node.isObject()) {
+ node.fields().forEachRemaining(entry -> details.put(entry.getKey(), entry.getValue().asText()));
+ }
+ return details;
+ }
+
+ private ObjectNode buildThingResponse(Thing thing) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingName", thing.getThingName());
+ response.put("thingArn", thing.getThingArn());
+ response.put("thingId", thing.getThingId());
+ response.put("thingTypeName", thing.getThingTypeName());
+ response.set("attributes", objectMapper.valueToTree(thing.getAttributes()));
+ response.put("version", thing.getVersion());
+ putEpoch(response, "creationDate", thing.getCreationDate());
+ putEpoch(response, "lastModifiedDate", thing.getLastModifiedDate());
+ return response;
+ }
+
+ private ObjectNode buildCertificateDescription(IotCertificate certificate) {
+ ObjectNode description = objectMapper.createObjectNode();
+ description.put("certificateArn", certificate.getCertificateArn());
+ description.put("certificateId", certificate.getCertificateId());
+ description.put("certificatePem", certificate.getCertificatePem());
+ description.put("status", certificate.getStatus());
+ putEpoch(description, "creationDate", certificate.getCreationDate());
+ return description;
+ }
+
+ private ObjectNode buildPolicyResponse(IotPolicy policy) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("policyName", policy.getPolicyName());
+ response.put("policyArn", policy.getPolicyArn());
+ response.put("policyDocument", policy.getPolicyDocument());
+ response.put("defaultVersionId", policy.getDefaultVersionId());
+ return response;
+ }
+
+ private ObjectNode buildPolicyVersionResponse(IotPolicy policy, IotPolicy.PolicyVersion version, boolean isDefault) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("policyArn", policy.getPolicyArn());
+ response.put("policyName", policy.getPolicyName());
+ response.put("policyDocument", version.getDocument());
+ response.put("policyVersionId", version.getVersionId());
+ response.put("isDefaultVersion", isDefault);
+ putEpoch(response, "creationDate", version.getCreateDate());
+ return response;
+ }
+
+ private ObjectNode buildPolicyVersionSummary(IotPolicy policy, IotPolicy.PolicyVersion version) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("versionId", version.getVersionId());
+ response.put("isDefaultVersion", version.getVersionId().equals(policy.getDefaultVersionId()));
+ putEpoch(response, "createDate", version.getCreateDate());
+ return response;
+ }
+
+ private ObjectNode buildJobResponse(IotJob job) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("jobArn", job.getJobArn());
+ response.put("jobId", job.getJobId());
+ response.put("targetSelection", job.getTargetSelection());
+ response.put("status", job.getStatus());
+ ArrayNode targets = response.putArray("targets");
+ job.getTargets().forEach(targets::add);
+ response.put("description", job.getDescription());
+ putEpoch(response, "createdAt", job.getCreatedAt());
+ putEpoch(response, "lastUpdatedAt", job.getLastUpdatedAt());
+ return response;
+ }
+
+ private ObjectNode buildThingTypeCreateResponse(IotThingType type) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingTypeName", type.getThingTypeName());
+ response.put("thingTypeArn", type.getThingTypeArn());
+ response.put("thingTypeId", type.getThingTypeId());
+ return response;
+ }
+
+ private ObjectNode buildThingTypeDescription(IotThingType type) {
+ ObjectNode response = buildThingTypeCreateResponse(type);
+ response.set("thingTypeProperties", buildThingTypeProperties(type));
+ ObjectNode metadata = response.putObject("thingTypeMetadata");
+ metadata.put("deprecated", type.isDeprecated());
+ putEpoch(metadata, "creationDate", type.getCreationDate());
+ putEpoch(metadata, "deprecatedDate", type.getDeprecatedDate());
+ return response;
+ }
+
+ private ObjectNode buildThingTypeSummary(IotThingType type) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingTypeName", type.getThingTypeName());
+ response.put("thingTypeArn", type.getThingTypeArn());
+ response.put("thingTypeId", type.getThingTypeId());
+ return response;
+ }
+
+ private ObjectNode buildThingTypeProperties(IotThingType type) {
+ ObjectNode properties = objectMapper.createObjectNode();
+ properties.put("thingTypeDescription", type.getDescription());
+ ArrayNode attrs = properties.putArray("searchableAttributes");
+ type.getSearchableAttributes().forEach(attrs::add);
+ return properties;
+ }
+
+ private ObjectNode buildThingGroupCreateResponse(IotThingGroup group) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingGroupName", group.getThingGroupName());
+ response.put("thingGroupArn", group.getThingGroupArn());
+ response.put("thingGroupId", group.getThingGroupId());
+ return response;
+ }
+
+ private ObjectNode buildThingGroupDescription(IotThingGroup group) {
+ ObjectNode response = buildThingGroupCreateResponse(group);
+ response.set("thingGroupProperties", buildThingGroupProperties(group));
+ response.put("version", group.getVersion());
+ ObjectNode metadata = response.putObject("thingGroupMetadata");
+ putEpoch(metadata, "creationDate", group.getCreationDate());
+ return response;
+ }
+
+ private ObjectNode buildThingGroupSummary(IotThingGroup group) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("groupName", group.getThingGroupName());
+ response.put("groupArn", group.getThingGroupArn());
+ return response;
+ }
+
+ private ObjectNode buildThingGroupProperties(IotThingGroup group) {
+ ObjectNode properties = objectMapper.createObjectNode();
+ properties.put("thingGroupDescription", group.getDescription());
+ ObjectNode attributePayload = properties.putObject("attributePayload");
+ attributePayload.set("attributes", objectMapper.valueToTree(group.getAttributes()));
+ return properties;
+ }
+
+ private ObjectNode buildJobSummary(IotJob job) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("jobArn", job.getJobArn());
+ response.put("jobId", job.getJobId());
+ response.put("targetSelection", job.getTargetSelection());
+ response.put("status", job.getStatus());
+ putEpoch(response, "createdAt", job.getCreatedAt());
+ putEpoch(response, "lastUpdatedAt", job.getLastUpdatedAt());
+ return response;
+ }
+
+ private ObjectNode jobExecutionResponse(IotJobExecution execution, IotJob job, boolean includeDocument) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ObjectNode executionNode = buildJobExecution(execution);
+ if (includeDocument && job.getDocument() != null) {
+ executionNode.put("jobDocument", job.getDocument());
+ }
+ response.set("execution", executionNode);
+ return response;
+ }
+
+ private ObjectNode buildJobExecution(IotJobExecution execution) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("jobId", execution.getJobId());
+ node.put("thingName", execution.getThingName());
+ node.put("thingArn", execution.getThingArn());
+ node.put("status", execution.getStatus());
+ node.set("statusDetails", objectMapper.valueToTree(execution.getStatusDetails()));
+ putEpochSeconds(node, "queuedAt", execution.getQueuedAt());
+ putEpochSeconds(node, "startedAt", execution.getStartedAt());
+ putEpochSeconds(node, "lastUpdatedAt", execution.getLastUpdatedAt());
+ node.put("executionNumber", execution.getExecutionNumber());
+ node.put("versionNumber", execution.getVersionNumber());
+ return node;
+ }
+
+ private ObjectNode buildJobExecutionSummary(IotJobExecution execution) {
+ ObjectNode summary = objectMapper.createObjectNode();
+ summary.put("status", execution.getStatus());
+ putEpochSeconds(summary, "queuedAt", execution.getQueuedAt());
+ putEpochSeconds(summary, "startedAt", execution.getStartedAt());
+ putEpochSeconds(summary, "lastUpdatedAt", execution.getLastUpdatedAt());
+ summary.put("executionNumber", execution.getExecutionNumber());
+ return summary;
+ }
+
+ private ObjectNode buildJobsDataExecutionSummary(IotJobExecution execution) {
+ ObjectNode summary = buildJobExecutionSummary(execution);
+ summary.put("jobId", execution.getJobId());
+ summary.put("versionNumber", execution.getVersionNumber());
+ return summary;
+ }
+
+ private ObjectNode buildTopicRuleResponse(IotTopicRule rule) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ruleName", rule.getRuleName());
+ response.put("sql", rule.getSql());
+ response.put("description", rule.getDescription());
+ response.put("ruleDisabled", rule.isRuleDisabled());
+ putEpoch(response, "createdAt", rule.getCreatedAt());
+ try {
+ response.set("actions", objectMapper.readTree(rule.getActionsJson()));
+ } catch (JsonProcessingException e) {
+ response.putArray("actions");
+ }
+ return response;
+ }
+
+ private String topicPattern(String sql) {
+ if (sql == null) {
+ return null;
+ }
+ int from = sql.toUpperCase().indexOf(" FROM ");
+ if (from < 0) {
+ return null;
+ }
+ String tail = sql.substring(from + " FROM ".length()).trim();
+ if (tail.length() >= 2 && (tail.charAt(0) == '\'' || tail.charAt(0) == '"')) {
+ char quote = tail.charAt(0);
+ int end = tail.indexOf(quote, 1);
+ if (end > 1) {
+ return tail.substring(1, end);
+ }
+ }
+ return null;
+ }
+
+ private void putEpoch(ObjectNode node, String field, Instant instant) {
+ if (instant != null) {
+ node.put(field, instant.toEpochMilli() / 1000.0);
+ }
+ }
+
+ private void putEpochSeconds(ObjectNode node, String field, Instant instant) {
+ if (instant != null) {
+ node.put(field, instant.getEpochSecond());
+ }
+ }
+
+ private record GroupMembershipRequest(String thingGroupName, String thingName) {
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotDataController.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotDataController.java
new file mode 100644
index 0000000000..71d9950f91
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotDataController.java
@@ -0,0 +1,191 @@
+package io.github.hectorvent.floci.services.iot;
+
+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.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
+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.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;
+
+import java.util.Base64;
+import java.util.UUID;
+
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+public class IotDataController {
+
+ private final IotService iotService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public IotDataController(IotService iotService, RegionResolver regionResolver, ObjectMapper objectMapper) {
+ this.iotService = iotService;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ }
+
+ @GET
+ @Path("/things/{thingName}/shadow")
+ public Response getThingShadow(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @QueryParam("name") String shadowName) {
+ return Response.ok(iotService.getThingShadow(thingName, shadowName, regionResolver.resolveRegion(headers))).build();
+ }
+
+ @POST
+ @Path("/things/{thingName}/shadow")
+ @Consumes(MediaType.WILDCARD)
+ public Response updateThingShadow(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @QueryParam("name") String shadowName,
+ String body) {
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ return Response.ok(iotService.updateThingShadow(thingName, shadowName, request, regionResolver.resolveRegion(headers))).build();
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @DELETE
+ @Path("/things/{thingName}/shadow")
+ public Response deleteThingShadow(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName,
+ @QueryParam("name") String shadowName) {
+ return Response.ok(iotService.deleteThingShadow(thingName, shadowName, regionResolver.resolveRegion(headers))).build();
+ }
+
+ @GET
+ @Path("/api/things/shadow/ListNamedShadowsForThing/{thingName}")
+ public Response listNamedShadowsForThing(@Context HttpHeaders headers,
+ @PathParam("thingName") String thingName) {
+ ObjectNode response = objectMapper.createObjectNode();
+ var results = response.putArray("results");
+ iotService.listNamedShadowsForThing(thingName, regionResolver.resolveRegion(headers)).forEach(results::add);
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/topics/{topic: .+}")
+ @Consumes(MediaType.WILDCARD)
+ public Response publish(@PathParam("topic") String topic,
+ @QueryParam("retain") Boolean retain,
+ @QueryParam("qos") Integer qos,
+ byte[] payload) {
+ iotService.publish(topic, payload == null ? new byte[0] : payload, Boolean.TRUE.equals(retain), qos == null ? 0 : qos);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @DELETE
+ @Path("/connections/{clientId: .+}")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteConnection(@PathParam("clientId") String clientId,
+ @QueryParam("cleanSession") Boolean cleanSession,
+ @QueryParam("preventWillMessage") Boolean preventWillMessage) {
+ iotService.deleteConnection(clientId, Boolean.TRUE.equals(cleanSession));
+ return Response.ok().build();
+ }
+
+ @GET
+ @Path("/connections/{clientId: .+}/subscriptions")
+ public Response listSubscriptions(@PathParam("clientId") String clientId,
+ @QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<String> page = iotService.listSubscriptions(clientId, maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ var subscriptions = response.putArray("subscriptions");
+ for (String topicFilter : page.items()) {
+ ObjectNode subscription = subscriptions.addObject();
+ subscription.put("topicFilter", topicFilter);
+ subscription.put("qos", 0);
+ }
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/connections/{clientId: .+}")
+ public Response getConnection(@PathParam("clientId") String clientId,
+ @QueryParam("includeSocketInformation") Boolean includeSocketInformation) {
+ IotMqttBrokerService.ConnectionInfo connection = iotService.getConnection(clientId);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("clientId", connection.clientId());
+ response.put("connected", true);
+ response.put("cleanSession", true);
+ if (Boolean.TRUE.equals(includeSocketInformation)) {
+ response.put("sourceIp", connection.address());
+ response.put("sourcePort", connection.port());
+ }
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/connections/{clientId: .+}/messages")
+ @Consumes(MediaType.WILDCARD)
+ public Response sendDirectMessage(@PathParam("clientId") String clientId,
+ @QueryParam("topic") String topic,
+ @QueryParam("confirmation") Boolean confirmation,
+ byte[] payload) {
+ iotService.sendDirectMessage(clientId, topic, payload);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("message", "OK");
+ response.put("traceId", UUID.randomUUID().toString());
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/retainedMessage/{topic: .+}")
+ public Response getRetainedMessage(@PathParam("topic") String topic) {
+ IotRetainedMessage retained = iotService.getRetainedMessage(topic);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("topic", retained.getTopic());
+ response.put("payload", retained.getPayload());
+ response.put("qos", retained.getQos());
+ putEpoch(response, "lastModifiedTime", retained.getLastModifiedTime());
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/retainedMessage")
+ public Response listRetainedMessages(@QueryParam("maxResults") Integer maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ IotService.Page<IotRetainedMessage> page = iotService.listRetainedMessages(maxResults, nextToken);
+ ObjectNode response = objectMapper.createObjectNode();
+ var topics = response.putArray("retainedTopics");
+ for (IotRetainedMessage retained : page.items()) {
+ ObjectNode item = topics.addObject();
+ item.put("topic", retained.getTopic());
+ item.put("payloadSize", Base64.getDecoder().decode(retained.getPayload()).length);
+ item.put("qos", retained.getQos());
+ putEpoch(item, "lastModifiedTime", retained.getLastModifiedTime());
+ }
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ private void putEpoch(ObjectNode node, String field, java.time.Instant instant) {
+ if (instant != null) {
+ node.put(field, instant.toEpochMilli() / 1000.0);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java
new file mode 100644
index 0000000000..9bb58cd3fe
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java
@@ -0,0 +1,325 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
+import io.netty.handler.codec.mqtt.MqttQoS;
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.vertx.core.Vertx;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.mqtt.MqttEndpoint;
+import io.vertx.mqtt.MqttServer;
+import io.vertx.mqtt.MqttServerOptions;
+import io.vertx.mqtt.messages.MqttPublishMessage;
+import io.vertx.mqtt.messages.MqttSubscribeMessage;
+import io.vertx.mqtt.messages.MqttUnsubscribeMessage;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+@ApplicationScoped
+public class IotMqttBrokerService {
+
+ private static final Logger LOG = Logger.getLogger(IotMqttBrokerService.class);
+
+ private final EmulatorConfig config;
+ private final Vertx vertx;
+ private final Instance<IotService> iotService;
+ private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
+ private final Map<String, Map<String, Subscription>> subscriptionsByClient = new ConcurrentHashMap<>();
+ private MqttServer server;
+
+ @Inject
+ public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService) {
+ this.config = config;
+ this.vertx = vertx;
+ this.iotService = iotService;
+ }
+
+ void onStart(@Observes StartupEvent ignored) {
+ if (!config.services().iot().enabled() || !config.services().iot().mqtt().enabled()) {
+ LOG.info("IoT MQTT broker disabled by configuration");
+ return;
+ }
+ if (!config.services().iot().mqtt().autoStart()) {
+ LOG.info("IoT MQTT broker auto-start disabled by configuration");
+ return;
+ }
+ startIfEnabled();
+ }
+
+ void onStop(@Observes ShutdownEvent ignored) {
+ stop();
+ }
+
+ synchronized void startIfEnabled() {
+ if (!config.services().iot().enabled() || !config.services().iot().mqtt().enabled()) {
+ return;
+ }
+ if (server != null) {
+ return;
+ }
+
+ MqttServer mqttServer = MqttServer.create(vertx, new MqttServerOptions()
+ .setHost(config.services().iot().mqtt().host())
+ .setPort(config.services().iot().mqtt().port()));
+ mqttServer.endpointHandler(this::handleEndpoint);
+ mqttServer.exceptionHandler(error -> LOG.warnv("IoT MQTT broker error: {0}", error.getMessage()));
+
+ try {
+ mqttServer.listen().toCompletionStage().toCompletableFuture().join();
+ server = mqttServer;
+ LOG.infov("IoT MQTT broker started on {0}:{1}",
+ config.services().iot().mqtt().host(), config.services().iot().mqtt().port());
+ } catch (Exception e) {
+ mqttServer.close();
+ throw new IllegalStateException("Failed to start IoT MQTT broker", e);
+ }
+ }
+
+ synchronized void stop() {
+ MqttServer mqttServer = server;
+ if (mqttServer == null) {
+ return;
+ }
+ server = null;
+ sessionsByClient.values().forEach(session -> session.endpoint().close());
+ sessionsByClient.clear();
+ subscriptionsByClient.clear();
+ mqttServer.close().toCompletionStage().toCompletableFuture().join();
+ LOG.info("IoT MQTT broker stopped");
+ }
+
+ public synchronized boolean isRunning() {
+ return server != null;
+ }
+
+ void publish(String topic, byte[] payload) {
+ if (server == null) {
+ return;
+ }
+ fanOut(topic, payload == null ? new byte[0] : payload, false);
+ }
+
+ boolean disconnectClient(String clientId, boolean cleanSession) {
+ ClientSession session = sessionsByClient.remove(clientId);
+ if (session == null) {
+ return false;
+ }
+ if (cleanSession) {
+ subscriptionsByClient.remove(clientId);
+ }
+ session.endpoint().close();
+ return true;
+ }
+
+ Optional<ConnectionInfo> getConnection(String clientId) {
+ if (server == null) {
+ return Optional.empty();
+ }
+ ClientSession session = sessionsByClient.get(clientId);
+ if (session == null || !session.endpoint().isConnected()) {
+ return Optional.empty();
+ }
+ return Optional.of(new ConnectionInfo(session.clientId(), session.sourceIp(), session.sourcePort()));
+ }
+
+ List<String> listSubscriptions(String clientId) {
+ return subscriptionsByClient.getOrDefault(clientId, Map.of()).keySet().stream()
+ .sorted()
+ .toList();
+ }
+
+ private void handleEndpoint(MqttEndpoint endpoint) {
+ String clientId = endpoint.clientIdentifier();
+ SocketAddress remoteAddress = endpoint.remoteAddress();
+ ClientSession session = new ClientSession(
+ clientId,
+ endpoint,
+ remoteAddress == null ? null : remoteAddress.host(),
+ remoteAddress == null ? -1 : remoteAddress.port(),
+ endpoint.isCleanSession());
+
+ endpoint.subscriptionAutoAck(false);
+ endpoint.publishAutoAck(false);
+ endpoint.exceptionHandler(error -> LOG.warnv("IoT MQTT client {0} error: {1}", clientId, error.getMessage()));
+ endpoint.subscribeHandler(message -> handleSubscribe(session, message));
+ endpoint.unsubscribeHandler(message -> handleUnsubscribe(session, message));
+ endpoint.publishHandler(message -> handlePublish(session, message));
+ endpoint.disconnectHandler(ignored -> removeSession(session));
+ endpoint.closeHandler(ignored -> removeSession(session));
+
+ ClientSession previous = sessionsByClient.put(clientId, session);
+ if (previous != null && previous.endpoint() != endpoint) {
+ previous.endpoint().close();
+ }
+
+ endpoint.accept();
+ }
+
+ private void handleSubscribe(ClientSession session, MqttSubscribeMessage message) {
+ Map<String, Subscription> clientSubscriptions = subscriptionsByClient.computeIfAbsent(
+ session.clientId(), ignored -> new ConcurrentHashMap<>());
+ List<MqttQoS> grantedQos = new ArrayList<>();
+ List<Subscription> accepted = new ArrayList<>();
+
+ for (io.vertx.mqtt.MqttTopicSubscription requested : message.topicSubscriptions()) {
+ String topicFilter = requested.topicName();
+ MqttQoS qos = requested.qualityOfService();
+ if (!isValidTopicFilter(topicFilter) || qos == MqttQoS.EXACTLY_ONCE) {
+ grantedQos.add(MqttQoS.FAILURE);
+ continue;
+ }
+
+ int granted = qos == MqttQoS.AT_LEAST_ONCE ? 1 : 0;
+ Subscription subscription = new Subscription(topicFilter, granted);
+ clientSubscriptions.put(topicFilter, subscription);
+ accepted.add(subscription);
+ grantedQos.add(granted == 1 ? MqttQoS.AT_LEAST_ONCE : MqttQoS.AT_MOST_ONCE);
+ }
+
+ session.endpoint().subscribeAcknowledge(message.messageId(), grantedQos);
+ deliverRetained(session, accepted);
+ }
+
+ private void handleUnsubscribe(ClientSession session, MqttUnsubscribeMessage message) {
+ Map<String, Subscription> clientSubscriptions = subscriptionsByClient.get(session.clientId());
+ if (clientSubscriptions != null) {
+ for (String topic : message.topics()) {
+ clientSubscriptions.remove(topic);
+ }
+ if (clientSubscriptions.isEmpty()) {
+ subscriptionsByClient.remove(session.clientId(), clientSubscriptions);
+ }
+ }
+ session.endpoint().unsubscribeAcknowledge(message.messageId());
+ }
+
+ private void handlePublish(ClientSession session, MqttPublishMessage message) {
+ byte[] payload = message.payload().getBytes();
+ if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
+ session.endpoint().close();
+ return;
+ }
+ if (message.qosLevel() == MqttQoS.AT_LEAST_ONCE) {
+ session.endpoint().publishAcknowledge(message.messageId());
+ }
+
+ String topic = message.topicName();
+ if (topic.startsWith("$aws/")) {
+ iotService.get().handleReservedMqttPublish(topic, payload, this::publish);
+ return;
+ }
+
+ iotService.get().publish(topic, payload, message.isRetain(), message.qosLevel().value());
+ fanOut(topic, payload, false);
+ }
+
+ private void fanOut(String topic, byte[] payload, boolean retained) {
+ byte[] safePayload = payload == null ? new byte[0] : payload.clone();
+ for (ClientSession session : sessionsByClient.values()) {
+ if (!session.endpoint().isConnected() || !hasMatchingSubscription(session.clientId(), topic)) {
+ continue;
+ }
+ session.endpoint().publish(topic, Buffer.buffer(safePayload), MqttQoS.AT_MOST_ONCE, false, retained);
+ }
+ }
+
+ private boolean hasMatchingSubscription(String clientId, String topic) {
+ Map<String, Subscription> subscriptions = subscriptionsByClient.get(clientId);
+ if (subscriptions == null) {
+ return false;
+ }
+ return subscriptions.values().stream().anyMatch(subscription -> topicMatches(subscription.topicFilter(), topic));
+ }
+
+ private void deliverRetained(ClientSession session, List<Subscription> subscriptions) {
+ if (subscriptions.isEmpty()) {
+ return;
+ }
+ Set<String> deliveredTopics = new HashSet<>();
+ for (IotRetainedMessage retained : iotService.get().listRetainedMessages(null, null).items()) {
+ if (!deliveredTopics.add(retained.getTopic())) {
+ continue;
+ }
+ boolean matches = subscriptions.stream()
+ .anyMatch(subscription -> topicMatches(subscription.topicFilter(), retained.getTopic()));
+ if (!matches) {
+ continue;
+ }
+ byte[] payload = Base64.getDecoder().decode(retained.getPayload());
+ session.endpoint().publish(retained.getTopic(), Buffer.buffer(payload), MqttQoS.AT_MOST_ONCE, false, true);
+ }
+ }
+
+ private void removeSession(ClientSession session) {
+ sessionsByClient.remove(session.clientId(), session);
+ if (session.cleanSession()) {
+ subscriptionsByClient.remove(session.clientId());
+ }
+ }
+
+ private boolean isValidTopicFilter(String topicFilter) {
+ if (topicFilter == null || topicFilter.isBlank()) {
+ return false;
+ }
+ String[] levels = topicFilter.split("/", -1);
+ for (int i = 0; i < levels.length; i++) {
+ String level = levels[i];
+ if (level.contains("#") && (!"#".equals(level) || i != levels.length - 1)) {
+ return false;
+ }
+ if (level.contains("+") && !"+".equals(level)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean topicMatches(String topicFilter, String topic) {
+ if (topicFilter.equals(topic)) {
+ return true;
+ }
+ String[] filterLevels = topicFilter.split("/", -1);
+ String[] topicLevels = topic.split("/", -1);
+ for (int i = 0; i < filterLevels.length; i++) {
+ String filterLevel = filterLevels[i];
+ if ("#".equals(filterLevel)) {
+ return i == filterLevels.length - 1;
+ }
+ if (i >= topicLevels.length) {
+ return false;
+ }
+ if (!"+".equals(filterLevel) && !filterLevel.equals(topicLevels[i])) {
+ return false;
+ }
+ }
+ return filterLevels.length == topicLevels.length;
+ }
+
+ private record ClientSession(
+ String clientId,
+ MqttEndpoint endpoint,
+ String sourceIp,
+ int sourcePort,
+ boolean cleanSession) {
+ }
+
+ private record Subscription(String topicFilter, int qos) {
+ }
+
+ record ConnectionInfo(String clientId, String address, int port) {
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEvent.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEvent.java
new file mode 100644
index 0000000000..c8ddf06d88
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEvent.java
@@ -0,0 +1,4 @@
+package io.github.hectorvent.floci.services.iot;
+
+public record IotPublishEvent(String topic, byte[] payload) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEventRecorder.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEventRecorder.java
new file mode 100644
index 0000000000..adf15eb488
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotPublishEventRecorder.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.iot;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@ApplicationScoped
+public class IotPublishEventRecorder {
+
+ private final List<IotPublishEvent> events = new ArrayList<>();
+
+ public synchronized void record(String topic, byte[] payload) {
+ events.add(new IotPublishEvent(topic, payload == null ? new byte[0] : payload.clone()));
+ }
+
+ public synchronized List<IotPublishEvent> recentEvents() {
+ return List.copyOf(events);
+ }
+
+ public synchronized void clear() {
+ events.clear();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
new file mode 100644
index 0000000000..04187effca
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -0,0 +1,1402 @@
+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.ObjectMapper;
+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.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.iot.model.IotCertificate;
+import io.github.hectorvent.floci.services.iot.model.IotJob;
+import io.github.hectorvent.floci.services.iot.model.IotJobExecution;
+import io.github.hectorvent.floci.services.iot.model.IotPolicy;
+import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
+import io.github.hectorvent.floci.services.iot.model.IotShadow;
+import io.github.hectorvent.floci.services.iot.model.IotThingGroup;
+import io.github.hectorvent.floci.services.iot.model.IotThingType;
+import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
+import io.github.hectorvent.floci.services.iot.model.Thing;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
+import io.github.hectorvent.floci.services.kinesis.KinesisService;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import io.github.hectorvent.floci.services.sns.SnsService;
+import io.github.hectorvent.floci.services.sqs.SqsService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.regex.Pattern;
+
+@ApplicationScoped
+public class IotService {
+
+ static final String DEFAULT_ENDPOINT_TYPE = "iot:Data-ATS";
+
+ private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
+
+ private final StorageBackend<String, Thing> thingStore;
+ private final StorageBackend<String, IotCertificate> certificateStore;
+ private final StorageBackend<String, IotPolicy> policyStore;
+ private final StorageBackend<String, Set<String>> policyAttachmentStore;
+ private final StorageBackend<String, Set<String>> thingPrincipalStore;
+ private final StorageBackend<String, IotShadow> shadowStore;
+ private final StorageBackend<String, IotTopicRule> topicRuleStore;
+ private final StorageBackend<String, IotRetainedMessage> retainedMessageStore;
+ private final StorageBackend<String, IotJob> jobStore;
+ private final StorageBackend<String, IotJobExecution> jobExecutionStore;
+ private final StorageBackend<String, IotThingType> thingTypeStore;
+ private final StorageBackend<String, IotThingGroup> thingGroupStore;
+ private final StorageBackend<String, Set<String>> thingGroupMembershipStore;
+ private final EmulatorConfig config;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+ private final IotPublishEventRecorder publishEventRecorder;
+ private final IotMqttBrokerService mqttBrokerService;
+ private final SqsService sqsService;
+ private final SnsService snsService;
+ private final S3Service s3Service;
+ private final KinesisService kinesisService;
+ private final DynamoDbService dynamoDbService;
+ private final LambdaService lambdaService;
+
+ @Inject
+ public IotService(StorageFactory storageFactory,
+ EmulatorConfig config,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper,
+ IotPublishEventRecorder publishEventRecorder,
+ IotMqttBrokerService mqttBrokerService,
+ SqsService sqsService,
+ SnsService snsService,
+ S3Service s3Service,
+ KinesisService kinesisService,
+ DynamoDbService dynamoDbService,
+ LambdaService lambdaService) {
+ this(storageFactory.create("iot", "iot-things.json", new TypeReference<Map<String, Thing>>() {}),
+ storageFactory.create("iot", "iot-certificates.json", new TypeReference<Map<String, IotCertificate>>() {}),
+ storageFactory.create("iot", "iot-policies.json", new TypeReference<Map<String, IotPolicy>>() {}),
+ storageFactory.create("iot", "iot-policy-attachments.json", new TypeReference<Map<String, Set<String>>>() {}),
+ storageFactory.create("iot", "iot-thing-principals.json", new TypeReference<Map<String, Set<String>>>() {}),
+ storageFactory.create("iot", "iot-shadows.json", new TypeReference<Map<String, IotShadow>>() {}),
+ storageFactory.create("iot", "iot-topic-rules.json", new TypeReference<Map<String, IotTopicRule>>() {}),
+ storageFactory.create("iot", "iot-retained-messages.json", new TypeReference<Map<String, IotRetainedMessage>>() {}),
+ storageFactory.create("iot", "iot-jobs.json", new TypeReference<Map<String, IotJob>>() {}),
+ storageFactory.create("iot", "iot-job-executions.json", new TypeReference<Map<String, IotJobExecution>>() {}),
+ storageFactory.create("iot", "iot-thing-types.json", new TypeReference<Map<String, IotThingType>>() {}),
+ storageFactory.create("iot", "iot-thing-groups.json", new TypeReference<Map<String, IotThingGroup>>() {}),
+ storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
+ config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService,
+ s3Service, kinesisService, dynamoDbService, lambdaService);
+ }
+
+ IotService(StorageBackend<String, Thing> thingStore,
+ StorageBackend<String, IotCertificate> certificateStore,
+ StorageBackend<String, IotPolicy> policyStore,
+ StorageBackend<String, Set<String>> policyAttachmentStore,
+ StorageBackend<String, Set<String>> thingPrincipalStore,
+ StorageBackend<String, IotShadow> shadowStore,
+ StorageBackend<String, IotTopicRule> topicRuleStore,
+ StorageBackend<String, IotRetainedMessage> retainedMessageStore,
+ StorageBackend<String, IotJob> jobStore,
+ StorageBackend<String, IotJobExecution> jobExecutionStore,
+ StorageBackend<String, IotThingType> thingTypeStore,
+ StorageBackend<String, IotThingGroup> thingGroupStore,
+ StorageBackend<String, Set<String>> thingGroupMembershipStore,
+ EmulatorConfig config,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper,
+ IotPublishEventRecorder publishEventRecorder,
+ IotMqttBrokerService mqttBrokerService,
+ SqsService sqsService,
+ SnsService snsService,
+ S3Service s3Service,
+ KinesisService kinesisService,
+ DynamoDbService dynamoDbService,
+ LambdaService lambdaService) {
+ this.thingStore = thingStore;
+ this.certificateStore = certificateStore;
+ this.policyStore = policyStore;
+ this.policyAttachmentStore = policyAttachmentStore;
+ this.thingPrincipalStore = thingPrincipalStore;
+ this.shadowStore = shadowStore;
+ this.topicRuleStore = topicRuleStore;
+ this.retainedMessageStore = retainedMessageStore;
+ this.jobStore = jobStore;
+ this.jobExecutionStore = jobExecutionStore;
+ this.thingTypeStore = thingTypeStore;
+ this.thingGroupStore = thingGroupStore;
+ this.thingGroupMembershipStore = thingGroupMembershipStore;
+ this.config = config;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ this.publishEventRecorder = publishEventRecorder;
+ this.mqttBrokerService = mqttBrokerService;
+ this.sqsService = sqsService;
+ this.snsService = snsService;
+ this.s3Service = s3Service;
+ this.kinesisService = kinesisService;
+ this.dynamoDbService = dynamoDbService;
+ this.lambdaService = lambdaService;
+ }
+
+ 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)) {
+ throw new AwsException("InvalidRequestException", "Unsupported endpoint type: " + effectiveType, 400);
+ }
+ startMqttIfEnabled();
+ URI baseUri = URI.create(config.effectiveBaseUrl());
+ return baseUri.getAuthority();
+ }
+
+ public Thing createThing(String thingName, Map<String, String> attributes, String region) {
+ return createThing(thingName, attributes, null, region);
+ }
+
+ public Thing createThing(String thingName, Map<String, String> attributes, String thingTypeName, String region) {
+ startMqttIfEnabled();
+ validateThingName(thingName);
+ if (thingTypeName != null && !thingTypeName.isBlank()) {
+ describeThingType(thingTypeName, region);
+ }
+ String key = thingKey(region, thingName);
+ Thing existing = thingStore.get(key).orElse(null);
+ if (existing != null) {
+ if (existing.getAttributes().equals(attributes)
+ && java.util.Objects.equals(existing.getThingTypeName(), blankToNull(thingTypeName))) {
+ return existing;
+ }
+ throw new AwsException("ResourceAlreadyExistsException", "Thing already exists: " + thingName, 409);
+ }
+
+ Instant now = Instant.now();
+ Thing thing = new Thing();
+ thing.setThingName(thingName);
+ thing.setThingArn(regionResolver.buildArn("iot", region, "thing/" + thingName));
+ thing.setThingId(UUID.randomUUID().toString());
+ thing.setAttributes(attributes);
+ thing.setThingTypeName(blankToNull(thingTypeName));
+ thing.setVersion(1L);
+ thing.setCreationDate(now);
+ thing.setLastModifiedDate(now);
+ thingStore.put(key, thing);
+ return thing;
+ }
+
+ public Thing describeThing(String thingName, String region) {
+ validateThingName(thingName);
+ return thingStore.get(thingKey(region, thingName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Thing not found: " + thingName, 404));
+ }
+
+ public List<Thing> listThings(String region) {
+ String prefix = "thing:" + region + ":";
+ return thingStore.scan(key -> key.startsWith(prefix)).stream()
+ .sorted(Comparator.comparing(Thing::getThingName))
+ .toList();
+ }
+
+ public Page<Thing> listThings(String region, Integer maxResults, String nextToken) {
+ return paginate(listThings(region), maxResults, nextToken);
+ }
+
+ public Thing updateThing(String thingName, Map<String, String> attributes, Long expectedVersion, String region) {
+ Thing thing = describeThing(thingName, region);
+ if (expectedVersion != null && thing.getVersion() != expectedVersion) {
+ throw new AwsException("VersionConflictException", "Thing version does not match expectedVersion", 409);
+ }
+ thing.setAttributes(attributes);
+ thing.setVersion(thing.getVersion() + 1);
+ thing.setLastModifiedDate(Instant.now());
+ thingStore.put(thingKey(region, thingName), thing);
+ return thing;
+ }
+
+ public void deleteThing(String thingName, String region) {
+ describeThing(thingName, region);
+ thingStore.delete(thingKey(region, thingName));
+ for (String key : thingGroupMembershipStore.keys()) {
+ if (key.startsWith("thing-group-membership:" + region + ":")) {
+ Set<String> members = new HashSet<>(thingGroupMembershipStore.get(key).orElse(Set.of()));
+ if (members.remove(thingName)) {
+ thingGroupMembershipStore.put(key, members);
+ }
+ }
+ }
+ }
+
+ public Map<String, String> listTagsForResource(String resourceArn) {
+ return new TreeMap<>(taggableForArn(resourceArn).tags());
+ }
+
+ public void tagResource(String resourceArn, Map<String, String> tags) {
+ TaggableResource resource = taggableForArn(resourceArn);
+ Map<String, String> updatedTags = new TreeMap<>(resource.tags());
+ updatedTags.putAll(tags);
+ resource.updateTags().accept(updatedTags);
+ }
+
+ public void untagResource(String resourceArn, List<String> tagKeys) {
+ TaggableResource resource = taggableForArn(resourceArn);
+ Map<String, String> updatedTags = new TreeMap<>(resource.tags());
+ tagKeys.forEach(updatedTags::remove);
+ resource.updateTags().accept(updatedTags);
+ }
+
+ public IotCertificate createKeysAndCertificate(boolean setAsActive, String region) {
+ startMqttIfEnabled();
+ return createCertificate(setAsActive, null, region);
+ }
+
+ public IotCertificate createCertificateFromCsr(String certificateSigningRequest, boolean setAsActive, String region) {
+ if (certificateSigningRequest == null || certificateSigningRequest.isBlank()) {
+ throw new AwsException("InvalidRequestException", "certificateSigningRequest is required", 400);
+ }
+ return createCertificate(setAsActive, certificateSigningRequest, region);
+ }
+
+ private IotCertificate createCertificate(boolean setAsActive, String certificateSigningRequest, String region) {
+ startMqttIfEnabled();
+ String id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
+ IotCertificate certificate = new IotCertificate();
+ certificate.setCertificateId(id);
+ certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + id));
+ certificate.setCertificatePem("-----BEGIN CERTIFICATE-----\n" + id + "\n-----END CERTIFICATE-----");
+ certificate.setPublicKey("-----BEGIN PUBLIC KEY-----\n" + (certificateSigningRequest == null ? id : certificateSigningRequest.hashCode()) + "\n-----END PUBLIC KEY-----");
+ certificate.setPrivateKey("-----BEGIN PRIVATE KEY-----\n" + id + "\n-----END PRIVATE KEY-----");
+ certificate.setStatus(setAsActive ? "ACTIVE" : "INACTIVE");
+ certificate.setCreationDate(Instant.now());
+ certificateStore.put(certificateKey(region, id), certificate);
+ return certificate;
+ }
+
+ public IotCertificate describeCertificate(String certificateId, String region) {
+ return certificateStore.get(certificateKey(region, certificateId))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Certificate not found: " + certificateId, 404));
+ }
+
+ public List<IotCertificate> listCertificates(String region) {
+ String prefix = "cert:" + region + ":";
+ return certificateStore.scan(key -> key.startsWith(prefix)).stream()
+ .sorted(Comparator.comparing(IotCertificate::getCertificateId))
+ .toList();
+ }
+
+ public void updateCertificate(String certificateId, String status, String region) {
+ IotCertificate certificate = describeCertificate(certificateId, region);
+ validateCertificateStatus(status);
+ certificate.setStatus(status);
+ certificateStore.put(certificateKey(region, certificateId), certificate);
+ }
+
+ public void deleteCertificate(String certificateId, String region) {
+ IotCertificate certificate = describeCertificate(certificateId, region);
+ if ("ACTIVE".equals(certificate.getStatus())) {
+ throw new AwsException("InvalidRequestException", "Cannot delete ACTIVE certificate", 400);
+ }
+ if (certificateHasAttachments(certificate.getCertificateArn(), region)) {
+ throw new AwsException("InvalidRequestException", "Cannot delete attached certificate", 400);
+ }
+ certificateStore.delete(certificateKey(region, certificateId));
+ }
+
+ public IotPolicy createPolicy(String policyName, String policyDocument, String region) {
+ startMqttIfEnabled();
+ if (policyStore.get(policyKey(region, policyName)).isPresent()) {
+ throw new AwsException("ResourceAlreadyExistsException", "Policy already exists: " + policyName, 409);
+ }
+ IotPolicy policy = new IotPolicy();
+ policy.setPolicyName(policyName);
+ policy.setPolicyArn(regionResolver.buildArn("iot", region, "policy/" + policyName));
+ policy.setPolicyDocument(policyDocument);
+ policy.setDefaultVersionId("1");
+ policy.setCreationDate(Instant.now());
+ IotPolicy.PolicyVersion version = new IotPolicy.PolicyVersion();
+ version.setVersionId("1");
+ version.setDocument(policyDocument);
+ version.setCreateDate(policy.getCreationDate());
+ policy.setVersions(List.of(version));
+ policyStore.put(policyKey(region, policyName), policy);
+ return policy;
+ }
+
+ public IotPolicy getPolicy(String policyName, String region) {
+ return policyStore.get(policyKey(region, policyName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Policy not found: " + policyName, 404));
+ }
+
+ public List<IotPolicy> listPolicies(String region) {
+ String prefix = "policy:" + region + ":";
+ return policyStore.scan(key -> key.startsWith(prefix)).stream()
+ .sorted(Comparator.comparing(IotPolicy::getPolicyName))
+ .toList();
+ }
+
+ public void deletePolicy(String policyName, String region) {
+ getPolicy(policyName, region);
+ if (!policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()).isEmpty()) {
+ throw new AwsException("InvalidRequestException", "Cannot delete attached policy", 400);
+ }
+ policyStore.delete(policyKey(region, policyName));
+ policyAttachmentStore.delete(policyAttachmentKey(region, policyName));
+ }
+
+ public IotPolicy.PolicyVersion createPolicyVersion(String policyName, String policyDocument, boolean setAsDefault, String region) {
+ IotPolicy policy = getPolicy(policyName, region);
+ int next = policy.getVersions().stream()
+ .map(IotPolicy.PolicyVersion::getVersionId)
+ .mapToInt(Integer::parseInt)
+ .max()
+ .orElse(0) + 1;
+ IotPolicy.PolicyVersion version = new IotPolicy.PolicyVersion();
+ version.setVersionId(Integer.toString(next));
+ version.setDocument(policyDocument);
+ version.setCreateDate(Instant.now());
+ List<IotPolicy.PolicyVersion> versions = new java.util.ArrayList<>(policy.getVersions());
+ versions.add(version);
+ policy.setVersions(versions);
+ if (setAsDefault) {
+ policy.setDefaultVersionId(version.getVersionId());
+ policy.setPolicyDocument(policyDocument);
+ }
+ policyStore.put(policyKey(region, policyName), policy);
+ return version;
+ }
+
+ public IotPolicy.PolicyVersion getPolicyVersion(String policyName, String versionId, String region) {
+ IotPolicy policy = getPolicy(policyName, region);
+ return policy.getVersions().stream()
+ .filter(version -> versionId.equals(version.getVersionId()))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Policy version not found: " + versionId, 404));
+ }
+
+ public List<IotPolicy.PolicyVersion> listPolicyVersions(String policyName, String region) {
+ return getPolicy(policyName, region).getVersions().stream()
+ .sorted(Comparator.comparing(IotPolicy.PolicyVersion::getVersionId))
+ .toList();
+ }
+
+ public void setDefaultPolicyVersion(String policyName, String versionId, String region) {
+ IotPolicy policy = getPolicy(policyName, region);
+ IotPolicy.PolicyVersion version = getPolicyVersion(policyName, versionId, region);
+ policy.setDefaultVersionId(versionId);
+ policy.setPolicyDocument(version.getDocument());
+ policyStore.put(policyKey(region, policyName), policy);
+ }
+
+ public void deletePolicyVersion(String policyName, String versionId, String region) {
+ IotPolicy policy = getPolicy(policyName, region);
+ if (versionId.equals(policy.getDefaultVersionId())) {
+ throw new AwsException("InvalidRequestException", "Cannot delete default policy version", 400);
+ }
+ List<IotPolicy.PolicyVersion> versions = policy.getVersions().stream()
+ .filter(version -> !versionId.equals(version.getVersionId()))
+ .toList();
+ if (versions.size() == policy.getVersions().size()) {
+ throw new AwsException("ResourceNotFoundException", "Policy version not found: " + versionId, 404);
+ }
+ policy.setVersions(versions);
+ policyStore.put(policyKey(region, policyName), policy);
+ }
+
+ public void attachPolicy(String policyName, String target, String region) {
+ getPolicy(policyName, region);
+ Set<String> targets = new HashSet<>(policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()));
+ targets.add(target);
+ policyAttachmentStore.put(policyAttachmentKey(region, policyName), targets);
+ }
+
+ public void detachPolicy(String policyName, String target, String region) {
+ Set<String> targets = new HashSet<>(policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()));
+ targets.remove(target);
+ policyAttachmentStore.put(policyAttachmentKey(region, policyName), targets);
+ }
+
+ public void attachThingPrincipal(String thingName, String principal, String region) {
+ describeThing(thingName, region);
+ if (principal == null || principal.isBlank()) {
+ throw new AwsException("InvalidRequestException", "Principal is required", 400);
+ }
+ Set<String> principals = new HashSet<>(thingPrincipalStore.get(thingPrincipalKey(region, thingName)).orElse(Set.of()));
+ principals.add(principal);
+ thingPrincipalStore.put(thingPrincipalKey(region, thingName), principals);
+ }
+
+ public void detachThingPrincipal(String thingName, String principal, String region) {
+ Set<String> principals = new HashSet<>(thingPrincipalStore.get(thingPrincipalKey(region, thingName)).orElse(Set.of()));
+ principals.remove(principal);
+ thingPrincipalStore.put(thingPrincipalKey(region, thingName), principals);
+ }
+
+ public Set<String> listThingPrincipals(String thingName, String region) {
+ describeThing(thingName, region);
+ return new java.util.TreeSet<>(thingPrincipalStore.get(thingPrincipalKey(region, thingName)).orElse(Set.of()));
+ }
+
+ public Set<String> listPrincipalThings(String principal, String region) {
+ String prefix = "thing-principal:" + region + ":";
+ Set<String> things = new java.util.TreeSet<>();
+ for (String key : thingPrincipalStore.keys()) {
+ if (key.startsWith(prefix) && thingPrincipalStore.get(key).orElse(Set.of()).contains(principal)) {
+ things.add(key.substring(prefix.length()));
+ }
+ }
+ return things;
+ }
+
+ public List<IotPolicy> listAttachedPolicies(String target, String region) {
+ String prefix = "policy-attachment:" + region + ":";
+ return policyAttachmentStore.keys().stream()
+ .filter(key -> key.startsWith(prefix) && policyAttachmentStore.get(key).orElse(Set.of()).contains(target))
+ .map(key -> key.substring(prefix.length()))
+ .map(policyName -> policyStore.get(policyKey(region, policyName)))
+ .flatMap(Optional::stream)
+ .sorted(Comparator.comparing(IotPolicy::getPolicyName))
+ .toList();
+ }
+
+ public Set<String> listTargetsForPolicy(String policyName, String region) {
+ getPolicy(policyName, region);
+ return new java.util.TreeSet<>(policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()));
+ }
+
+ public JsonNode getThingShadow(String thingName, String shadowName, String region) {
+ IotShadow shadow = shadowStore.get(shadowKey(region, thingName, shadowName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shadow not found: " + thingName, 404));
+ return readJson(shadow.getDocument());
+ }
+
+ public JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String region) {
+ String key = shadowKey(region, thingName, shadowName);
+ IotShadow existing = shadowStore.get(key).orElse(null);
+ ObjectNode document = existing == null ? objectMapper.createObjectNode() : (ObjectNode) readJson(existing.getDocument()).deepCopy();
+ long currentVersion = existing == null ? 0 : existing.getVersion();
+ if (request.hasNonNull("version") && request.path("version").asLong() != currentVersion) {
+ throw new AwsException("VersionConflictException", "Shadow version does not match requested version", 409);
+ }
+ ObjectNode state = document.withObject("/state");
+ JsonNode requestState = request.path("state");
+ mergeObject(state, "desired", requestState.path("desired"));
+ mergeObject(state, "reported", requestState.path("reported"));
+ long version = currentVersion + 1;
+ document.put("version", version);
+ document.put("timestamp", Instant.now().getEpochSecond());
+
+ IotShadow shadow = new IotShadow();
+ shadow.setThingName(thingName);
+ shadow.setShadowName(shadowName);
+ shadow.setVersion(version);
+ shadow.setDocument(document.toString());
+ shadowStore.put(key, shadow);
+ return document;
+ }
+
+ public JsonNode deleteThingShadow(String thingName, String shadowName, String region) {
+ JsonNode document = getThingShadow(thingName, shadowName, region);
+ shadowStore.delete(shadowKey(region, thingName, shadowName));
+ return document;
+ }
+
+ public List<String> listNamedShadowsForThing(String thingName, String region) {
+ String prefix = "shadow:" + region + ":" + thingName + ":";
+ return shadowStore.scan(key -> key.startsWith(prefix)).stream()
+ .map(IotShadow::getShadowName)
+ .filter(name -> name != null && !name.isBlank())
+ .sorted()
+ .toList();
+ }
+
+ public void publish(String topic, byte[] payload) {
+ publish(topic, payload, false, 0);
+ }
+
+ public void publish(String topic, byte[] payload, boolean retain, int qos) {
+ byte[] eventPayload = payload == null ? new byte[0] : payload;
+ if (retain) {
+ if (eventPayload.length == 0) {
+ retainedMessageStore.delete(retainedMessageKey(topic));
+ } else {
+ IotRetainedMessage retained = new IotRetainedMessage();
+ retained.setTopic(topic);
+ retained.setPayload(Base64.getEncoder().encodeToString(eventPayload));
+ retained.setQos(qos);
+ retained.setLastModifiedTime(Instant.now());
+ retainedMessageStore.put(retainedMessageKey(topic), retained);
+ }
+ }
+ handlePublish(topic, eventPayload, true);
+ }
+
+ public void deleteConnection(String clientId, boolean cleanSession) {
+ validateMqttClientId(clientId);
+ boolean disconnected = mqttBrokerService.disconnectClient(clientId, cleanSession);
+ if (!disconnected) {
+ throw new AwsException("ResourceNotFoundException", "MQTT client is not connected: " + clientId, 404);
+ }
+ }
+
+ public IotMqttBrokerService.ConnectionInfo getConnection(String clientId) {
+ validateMqttClientId(clientId);
+ return mqttBrokerService.getConnection(clientId)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "MQTT client is not connected: " + clientId, 404));
+ }
+
+ public Page<String> listSubscriptions(String clientId, Integer maxResults, String nextToken) {
+ getConnection(clientId);
+ return paginate(mqttBrokerService.listSubscriptions(clientId), maxResults, nextToken);
+ }
+
+ public void sendDirectMessage(String clientId, String topic, byte[] payload) {
+ getConnection(clientId);
+ if (topic == null || topic.isBlank()) {
+ throw new AwsException("InvalidRequestException", "topic is required", 400);
+ }
+ mqttBrokerService.publish(topic, payload == null ? new byte[0] : payload);
+ }
+
+ public IotRetainedMessage getRetainedMessage(String topic) {
+ return retainedMessageStore.get(retainedMessageKey(topic))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Retained message not found: " + topic, 404));
+ }
+
+ public Page<IotRetainedMessage> listRetainedMessages(Integer maxResults, String nextToken) {
+ List<IotRetainedMessage> messages = retainedMessageStore.scan(key -> key.startsWith("retained:")).stream()
+ .sorted(Comparator.comparing(IotRetainedMessage::getTopic))
+ .toList();
+ return paginate(messages, maxResults, nextToken);
+ }
+
+ public IotThingType createThingType(String thingTypeName, JsonNode properties, String region) {
+ String key = thingTypeKey(region, thingTypeName);
+ IotThingType existing = thingTypeStore.get(key).orElse(null);
+ if (existing != null) {
+ if (java.util.Objects.equals(existing.getDescription(), properties.path("thingTypeDescription").asText(null))
+ && existing.getSearchableAttributes().equals(stringList(properties.path("searchableAttributes")))) {
+ return existing;
+ }
+ throw new AwsException("ResourceAlreadyExistsException", "Thing type already exists: " + thingTypeName, 409);
+ }
+ IotThingType type = new IotThingType();
+ type.setThingTypeName(thingTypeName);
+ type.setThingTypeArn(regionResolver.buildArn("iot", region, "thingtype/" + thingTypeName));
+ type.setThingTypeId(UUID.randomUUID().toString());
+ updateThingTypeProperties(type, properties);
+ type.setCreationDate(Instant.now());
+ thingTypeStore.put(key, type);
+ return type;
+ }
+
+ public IotThingType describeThingType(String thingTypeName, String region) {
+ return thingTypeStore.get(thingTypeKey(region, thingTypeName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Thing type not found: " + thingTypeName, 404));
+ }
+
+ public Page<IotThingType> listThingTypes(String region, Integer maxResults, String nextToken) {
+ return paginate(thingTypeStore.scan(key -> key.startsWith("thing-type:" + region + ":")).stream()
+ .sorted(Comparator.comparing(IotThingType::getThingTypeName))
+ .toList(), maxResults, nextToken);
+ }
+
+ public IotThingType updateThingType(String thingTypeName, JsonNode properties, String region) {
+ IotThingType type = describeThingType(thingTypeName, region);
+ updateThingTypeProperties(type, properties);
+ thingTypeStore.put(thingTypeKey(region, thingTypeName), type);
+ return type;
+ }
+
+ public void deprecateThingType(String thingTypeName, String region) {
+ IotThingType type = describeThingType(thingTypeName, region);
+ type.setDeprecated(true);
+ type.setDeprecatedDate(Instant.now());
+ thingTypeStore.put(thingTypeKey(region, thingTypeName), type);
+ }
+
+ public void deleteThingType(String thingTypeName, String region) {
+ describeThingType(thingTypeName, region);
+ boolean inUse = listThings(region).stream().anyMatch(thing -> thingTypeName.equals(thing.getThingTypeName()));
+ if (inUse) {
+ throw new AwsException("InvalidRequestException", "Cannot delete thing type with associated things", 400);
+ }
+ thingTypeStore.delete(thingTypeKey(region, thingTypeName));
+ }
+
+ public IotThingGroup createThingGroup(String thingGroupName, JsonNode properties, String region) {
+ String key = thingGroupKey(region, thingGroupName);
+ IotThingGroup existing = thingGroupStore.get(key).orElse(null);
+ if (existing != null) {
+ if (java.util.Objects.equals(existing.getDescription(), properties.path("thingGroupDescription").asText(null))
+ && existing.getAttributes().equals(parseAttributePayload(properties.path("attributePayload")))) {
+ return existing;
+ }
+ throw new AwsException("ResourceAlreadyExistsException", "Thing group already exists: " + thingGroupName, 409);
+ }
+ IotThingGroup group = new IotThingGroup();
+ group.setThingGroupName(thingGroupName);
+ group.setThingGroupArn(regionResolver.buildArn("iot", region, "thinggroup/" + thingGroupName));
+ group.setThingGroupId(UUID.randomUUID().toString());
+ group.setCreationDate(Instant.now());
+ updateThingGroupProperties(group, properties);
+ thingGroupStore.put(key, group);
+ return group;
+ }
+
+ public IotThingGroup describeThingGroup(String thingGroupName, String region) {
+ return thingGroupStore.get(thingGroupKey(region, thingGroupName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Thing group not found: " + thingGroupName, 404));
+ }
+
+ public Page<IotThingGroup> listThingGroups(String region, Integer maxResults, String nextToken) {
+ return paginate(thingGroupStore.scan(key -> key.startsWith("thing-group:" + region + ":")).stream()
+ .sorted(Comparator.comparing(IotThingGroup::getThingGroupName))
+ .toList(), maxResults, nextToken);
+ }
+
+ public IotThingGroup updateThingGroup(String thingGroupName, JsonNode properties, Long expectedVersion, String region) {
+ IotThingGroup group = describeThingGroup(thingGroupName, region);
+ if (expectedVersion != null && group.getVersion() != expectedVersion) {
+ throw new AwsException("VersionConflictException", "Thing group version does not match expectedVersion", 409);
+ }
+ updateThingGroupProperties(group, properties);
+ group.setVersion(group.getVersion() + 1);
+ thingGroupStore.put(thingGroupKey(region, thingGroupName), group);
+ return group;
+ }
+
+ public void deleteThingGroup(String thingGroupName, String region) {
+ describeThingGroup(thingGroupName, region);
+ thingGroupStore.delete(thingGroupKey(region, thingGroupName));
+ thingGroupMembershipStore.delete(thingGroupMembershipKey(region, thingGroupName));
+ }
+
+ public void addThingToThingGroup(String thingGroupName, String thingName, String region) {
+ describeThingGroup(thingGroupName, region);
+ describeThing(thingName, region);
+ Set<String> members = new HashSet<>(thingGroupMembershipStore.get(thingGroupMembershipKey(region, thingGroupName)).orElse(Set.of()));
+ members.add(thingName);
+ thingGroupMembershipStore.put(thingGroupMembershipKey(region, thingGroupName), members);
+ }
+
+ public void removeThingFromThingGroup(String thingGroupName, String thingName, String region) {
+ describeThingGroup(thingGroupName, region);
+ Set<String> members = new HashSet<>(thingGroupMembershipStore.get(thingGroupMembershipKey(region, thingGroupName)).orElse(Set.of()));
+ members.remove(thingName);
+ thingGroupMembershipStore.put(thingGroupMembershipKey(region, thingGroupName), members);
+ }
+
+ public Set<String> listThingsInThingGroup(String thingGroupName, String region) {
+ describeThingGroup(thingGroupName, region);
+ return new java.util.TreeSet<>(thingGroupMembershipStore.get(thingGroupMembershipKey(region, thingGroupName)).orElse(Set.of()));
+ }
+
+ public List<IotThingGroup> listThingGroupsForThing(String thingName, String region) {
+ describeThing(thingName, region);
+ String prefix = "thing-group-membership:" + region + ":";
+ return thingGroupMembershipStore.keys().stream()
+ .filter(key -> key.startsWith(prefix) && thingGroupMembershipStore.get(key).orElse(Set.of()).contains(thingName))
+ .map(key -> key.substring(prefix.length()))
+ .map(groupName -> thingGroupStore.get(thingGroupKey(region, groupName)))
+ .flatMap(Optional::stream)
+ .sorted(Comparator.comparing(IotThingGroup::getThingGroupName))
+ .toList();
+ }
+
+ public IotJob createJob(String jobId, JsonNode request, String region) {
+ startMqttIfEnabled();
+ if (jobStore.get(jobKey(region, jobId)).isPresent()) {
+ throw new AwsException("ResourceAlreadyExistsException", "Job already exists: " + jobId, 409);
+ }
+ JsonNode targetsNode = request.path("targets");
+ if (!targetsNode.isArray() || targetsNode.isEmpty()) {
+ throw new AwsException("InvalidRequestException", "targets is required", 400);
+ }
+
+ Instant now = Instant.now();
+ IotJob job = new IotJob();
+ job.setJobId(jobId);
+ job.setJobArn(regionResolver.buildArn("iot", region, "job/" + jobId));
+ job.setDocument(request.path("document").asText(null));
+ job.setDocumentSource(request.path("documentSource").asText(null));
+ job.setDescription(request.path("description").asText(null));
+ job.setTargetSelection(request.path("targetSelection").asText("SNAPSHOT"));
+ job.setCreatedAt(now);
+ job.setLastUpdatedAt(now);
+
+ List<String> targets = new java.util.ArrayList<>();
+ Set<String> thingNames = new java.util.TreeSet<>();
+ targetsNode.forEach(target -> {
+ String value = target.asText();
+ if (value != null && !value.isBlank()) {
+ targets.add(value);
+ thingNames.addAll(thingNamesForJobTarget(value, region));
+ }
+ });
+ if (thingNames.isEmpty()) {
+ throw new AwsException("ResourceNotFoundException", "No job targets found", 404);
+ }
+ job.setTargets(targets);
+ jobStore.put(jobKey(region, jobId), job);
+
+ for (String thingName : thingNames) {
+ Thing thing = describeThing(thingName, region);
+ IotJobExecution execution = new IotJobExecution();
+ execution.setJobId(jobId);
+ execution.setThingName(thingName);
+ execution.setThingArn(thing.getThingArn());
+ execution.setStatus("QUEUED");
+ execution.setQueuedAt(now);
+ execution.setLastUpdatedAt(now);
+ jobExecutionStore.put(jobExecutionKey(region, thingName, jobId), execution);
+ }
+ return job;
+ }
+
+ public IotJob describeJob(String jobId, String region) {
+ return jobStore.get(jobKey(region, jobId))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Job not found: " + jobId, 404));
+ }
+
+ public Page<IotJob> listJobs(String region, Integer maxResults, String nextToken) {
+ List<IotJob> jobs = jobStore.scan(key -> key.startsWith("job:" + region + ":")).stream()
+ .sorted(Comparator.comparing(IotJob::getJobId))
+ .toList();
+ return paginate(jobs, maxResults, nextToken);
+ }
+
+ public Page<IotJobExecution> listJobExecutionsForThing(String thingName, String region, Integer maxResults, String nextToken) {
+ describeThing(thingName, region);
+ List<IotJobExecution> executions = jobExecutionStore.scan(key -> key.startsWith("job-execution:" + region + ":" + thingName + ":")).stream()
+ .sorted(Comparator.comparing(IotJobExecution::getJobId))
+ .toList();
+ return paginate(executions, maxResults, nextToken);
+ }
+
+ public IotJobExecution describeJobExecution(String thingName, String jobId, String region) {
+ describeThing(thingName, region);
+ describeJob(jobId, region);
+ return jobExecutionStore.get(jobExecutionKey(region, thingName, jobId))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Job execution not found: " + jobId, 404));
+ }
+
+ public IotJobExecution startNextPendingJobExecution(String thingName, Map<String, String> statusDetails, String region) {
+ IotJobExecution execution = listJobExecutionsForThing(thingName, region, null, null).items().stream()
+ .filter(item -> "QUEUED".equals(item.getStatus()) || "IN_PROGRESS".equals(item.getStatus()))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No pending job executions for thing: " + thingName, 404));
+ if ("QUEUED".equals(execution.getStatus())) {
+ execution.setStatus("IN_PROGRESS");
+ execution.setStartedAt(Instant.now());
+ execution.setVersionNumber(execution.getVersionNumber() + 1);
+ }
+ if (statusDetails != null && !statusDetails.isEmpty()) {
+ execution.setStatusDetails(statusDetails);
+ }
+ execution.setLastUpdatedAt(Instant.now());
+ jobExecutionStore.put(jobExecutionKey(region, thingName, execution.getJobId()), execution);
+ return execution;
+ }
+
+ public IotJobExecution updateJobExecution(String thingName, String jobId, String status, Map<String, String> statusDetails,
+ Long expectedVersion, String region) {
+ IotJobExecution execution = describeJobExecution(thingName, jobId, region);
+ validateJobExecutionStatus(status);
+ if (expectedVersion != null && execution.getVersionNumber() != expectedVersion) {
+ throw new AwsException("VersionConflictException", "Job execution version does not match expectedVersion", 409);
+ }
+ if (Set.of("SUCCEEDED", "FAILED", "TIMED_OUT", "REJECTED", "REMOVED", "CANCELED").contains(execution.getStatus())) {
+ throw new AwsException("InvalidStateTransitionException", "Job execution is already terminal", 409);
+ }
+ execution.setStatus(status);
+ if ("IN_PROGRESS".equals(status) && execution.getStartedAt() == null) {
+ execution.setStartedAt(Instant.now());
+ }
+ if (statusDetails != null) {
+ execution.setStatusDetails(statusDetails);
+ }
+ execution.setVersionNumber(execution.getVersionNumber() + 1);
+ execution.setLastUpdatedAt(Instant.now());
+ jobExecutionStore.put(jobExecutionKey(region, thingName, jobId), execution);
+ return execution;
+ }
+
+ public IotTopicRule createTopicRule(String ruleName, JsonNode payload, String region) {
+ if (topicRuleStore.get(topicRuleKey(region, ruleName)).isPresent()) {
+ throw new AwsException("ResourceAlreadyExistsException", "Topic rule already exists: " + ruleName, 409);
+ }
+ return buildAndStoreTopicRule(ruleName, payload, region, Instant.now());
+ }
+
+ public IotTopicRule replaceTopicRule(String ruleName, JsonNode payload, String region) {
+ IotTopicRule existing = getTopicRule(ruleName, region);
+ IotTopicRule replacement = buildAndStoreTopicRule(ruleName, payload, region, existing.getCreatedAt());
+ replacement.setTags(existing.getTags());
+ topicRuleStore.put(topicRuleKey(region, ruleName), replacement);
+ return replacement;
+ }
+
+ private IotTopicRule buildAndStoreTopicRule(String ruleName, JsonNode payload, String region, Instant createdAt) {
+ IotTopicRule rule = new IotTopicRule();
+ rule.setRuleName(ruleName);
+ rule.setRuleArn(regionResolver.buildArn("iot", region, "rule/" + ruleName));
+ rule.setSql(payload.path("sql").asText());
+ rule.setDescription(payload.path("description").asText(null));
+ rule.setRuleDisabled(payload.path("ruleDisabled").asBoolean(false));
+ JsonNode actions = payload.path("actions");
+ rule.setActionsJson(actions.isArray() ? actions.toString() : "[]");
+ rule.setCreatedAt(createdAt == null ? Instant.now() : createdAt);
+ topicRuleStore.put(topicRuleKey(region, ruleName), rule);
+ return rule;
+ }
+
+ public IotTopicRule getTopicRule(String ruleName, String region) {
+ return topicRuleStore.get(topicRuleKey(region, ruleName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Topic rule not found: " + ruleName, 404));
+ }
+
+ public List<IotTopicRule> listTopicRules(String region) {
+ String prefix = "topic-rule:" + region + ":";
+ return topicRuleStore.scan(key -> key.startsWith(prefix)).stream()
+ .sorted(Comparator.comparing(IotTopicRule::getRuleName))
+ .toList();
+ }
+
+ public void deleteTopicRule(String ruleName, String region) {
+ getTopicRule(ruleName, region);
+ topicRuleStore.delete(topicRuleKey(region, ruleName));
+ }
+
+ public void setTopicRuleEnabled(String ruleName, boolean enabled, String region) {
+ IotTopicRule rule = getTopicRule(ruleName, region);
+ rule.setRuleDisabled(!enabled);
+ topicRuleStore.put(topicRuleKey(region, ruleName), rule);
+ }
+
+ void handlePublish(String topic, byte[] payload, boolean evaluateRules) {
+ byte[] eventPayload = payload == null ? new byte[0] : payload;
+ publishEventRecorder.record(topic, eventPayload);
+ if (!evaluateRules) {
+ return;
+ }
+ for (IotTopicRule rule : listTopicRules(config.defaultRegion())) {
+ if (!rule.isRuleDisabled() && topicMatches(extractTopicPattern(rule.getSql()), topic)) {
+ executeTopicRule(rule, eventPayload);
+ }
+ }
+ }
+
+ void handleReservedMqttPublish(String topic, byte[] payload, BiConsumer<String, byte[]> publisher) {
+ ReservedShadowTopic shadowTopic = parseReservedShadowTopic(topic);
+ if (shadowTopic == null) {
+ return;
+ }
+
+ try {
+ JsonNode request = readJson(payload == null || payload.length == 0 ? "{}" : new String(payload, java.nio.charset.StandardCharsets.UTF_8));
+ String clientToken = request.path("clientToken").asText(null);
+ String region = config.defaultRegion();
+ switch (shadowTopic.operation()) {
+ case "update" -> publishShadowUpdate(shadowTopic, request, clientToken, region, publisher);
+ case "get" -> publishShadowGet(shadowTopic, clientToken, region, publisher);
+ case "delete" -> publishShadowDelete(shadowTopic, clientToken, region, publisher);
+ default -> publishRejected(shadowTopic.rejectedTopic(), "InvalidRequestException",
+ "Unsupported shadow operation: " + shadowTopic.operation(), clientToken, publisher);
+ }
+ } catch (AwsException e) {
+ publishRejected(shadowTopic.rejectedTopic(), e.getErrorCode(), e.getMessage(), null, publisher);
+ } catch (Exception e) {
+ publishRejected(shadowTopic.rejectedTopic(), "InvalidRequestException", e.getMessage(), null, publisher);
+ }
+ }
+
+ private void validateThingName(String thingName) {
+ if (thingName == null || !THING_NAME_PATTERN.matcher(thingName).matches()) {
+ throw new AwsException("InvalidRequestException", "Invalid thing name: " + thingName, 400);
+ }
+ }
+
+ private void validateMqttClientId(String clientId) {
+ if (clientId == null || clientId.isBlank() || clientId.length() > 128 || clientId.startsWith("$")) {
+ throw new AwsException("InvalidRequestException", "Invalid MQTT clientId: " + clientId, 400);
+ }
+ }
+
+ private String thingKey(String region, String thingName) {
+ return "thing:" + region + ":" + thingName;
+ }
+
+ private <T> Page<T> paginate(List<T> items, Integer maxResults, String nextToken) {
+ int start = parseNextToken(nextToken);
+ if (start > items.size()) {
+ start = items.size();
+ }
+ int limit = maxResults == null ? items.size() - start : Math.max(0, maxResults);
+ int end = Math.min(items.size(), start + limit);
+ String followingToken = end < items.size() ? Integer.toString(end) : null;
+ return new Page<>(items.subList(start, end), followingToken);
+ }
+
+ private int parseNextToken(String nextToken) {
+ if (nextToken == null || nextToken.isBlank()) {
+ return 0;
+ }
+ try {
+ return Math.max(0, Integer.parseInt(nextToken));
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidRequestException", "Invalid nextToken", 400);
+ }
+ }
+
+ private void startMqttIfEnabled() {
+ mqttBrokerService.startIfEnabled();
+ }
+
+ private String certificateKey(String region, String certificateId) { return "cert:" + region + ":" + certificateId; }
+ private String policyKey(String region, String policyName) { return "policy:" + region + ":" + policyName; }
+ private String policyAttachmentKey(String region, String policyName) { return "policy-attachment:" + region + ":" + policyName; }
+ private String thingPrincipalKey(String region, String thingName) { return "thing-principal:" + region + ":" + thingName; }
+ private String shadowKey(String region, String thingName, String shadowName) { return "shadow:" + region + ":" + thingName + ":" + (shadowName == null ? "" : shadowName); }
+ private String topicRuleKey(String region, String ruleName) { return "topic-rule:" + region + ":" + ruleName; }
+ private String retainedMessageKey(String topic) { return "retained:" + topic; }
+ private String jobKey(String region, String jobId) { return "job:" + region + ":" + jobId; }
+ private String jobExecutionKey(String region, String thingName, String jobId) { return "job-execution:" + region + ":" + thingName + ":" + jobId; }
+ private String thingTypeKey(String region, String thingTypeName) { return "thing-type:" + region + ":" + thingTypeName; }
+ private String thingGroupKey(String region, String thingGroupName) { return "thing-group:" + region + ":" + thingGroupName; }
+ private String thingGroupMembershipKey(String region, String thingGroupName) { return "thing-group-membership:" + region + ":" + thingGroupName; }
+
+ private JsonNode readJson(String json) {
+ try {
+ return objectMapper.readTree(json);
+ } catch (Exception e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private void executeTopicRule(IotTopicRule rule, byte[] payload) {
+ try {
+ JsonNode actions = objectMapper.readTree(rule.getActionsJson());
+ if (!actions.isArray()) {
+ return;
+ }
+ for (JsonNode action : actions) {
+ JsonNode republish = action.path("republish");
+ if (republish.isObject()) {
+ String targetTopic = republish.path("topic").asText(null);
+ if (targetTopic != null && !targetTopic.isBlank()) {
+ handlePublish(targetTopic, payload, false);
+ mqttBrokerService.publish(targetTopic, payload);
+ }
+ }
+ JsonNode sqs = action.path("sqs");
+ if (sqs.isObject()) {
+ String queueUrl = sqs.path("queueUrl").asText(null);
+ if (queueUrl != null && !queueUrl.isBlank()) {
+ String body = sqs.path("useBase64").asBoolean(false)
+ ? Base64.getEncoder().encodeToString(payload)
+ : new String(payload, StandardCharsets.UTF_8);
+ sqsService.sendMessage(queueUrl, body, 0, config.defaultRegion());
+ }
+ }
+ JsonNode sns = action.path("sns");
+ if (sns.isObject()) {
+ String targetArn = sns.path("targetArn").asText(null);
+ if (targetArn != null && !targetArn.isBlank()) {
+ snsService.publish(targetArn, null, new String(payload, StandardCharsets.UTF_8), null, config.defaultRegion());
+ }
+ }
+ JsonNode s3 = action.path("s3");
+ if (s3.isObject()) {
+ String bucketName = s3.path("bucketName").asText(null);
+ String key = s3.path("key").asText(null);
+ if (bucketName != null && !bucketName.isBlank() && key != null && !key.isBlank()) {
+ s3Service.putObject(bucketName, key, payload, "application/octet-stream", Map.of());
+ }
+ }
+ JsonNode kinesis = action.path("kinesis");
+ if (kinesis.isObject()) {
+ String streamName = kinesis.path("streamName").asText(null);
+ String partitionKey = kinesis.path("partitionKey").asText("floci-iot");
+ if (streamName != null && !streamName.isBlank()) {
+ kinesisService.putRecord(streamName, payload, partitionKey, config.defaultRegion());
+ }
+ }
+ JsonNode dynamoDBv2 = action.path("dynamoDBv2");
+ if (dynamoDBv2.isObject()) {
+ String tableName = dynamoDBv2.path("putItem").path("tableName").asText(null);
+ if (tableName != null && !tableName.isBlank()) {
+ dynamoDbService.putItem(tableName, toDynamoDbItem(payload), config.defaultRegion());
+ }
+ }
+ JsonNode lambda = action.path("lambda");
+ if (lambda.isObject()) {
+ String functionArn = lambda.path("functionArn").asText(null);
+ if (functionArn != null && !functionArn.isBlank()) {
+ lambdaService.invoke(config.defaultRegion(), functionArn, payload, InvocationType.Event);
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new AwsException("InvalidRequestException", "Invalid topic rule action for " + rule.getRuleName() + ": " + e.getMessage(), 400);
+ }
+ }
+
+ private ObjectNode toDynamoDbItem(byte[] payload) {
+ try {
+ JsonNode document = objectMapper.readTree(payload);
+ if (!document.isObject()) {
+ throw new AwsException("InvalidRequestException", "dynamoDBv2 action payload must be a JSON object", 400);
+ }
+ ObjectNode item = objectMapper.createObjectNode();
+ document.fields().forEachRemaining(entry -> item.set(entry.getKey(), toDynamoDbAttribute(entry.getValue())));
+ return item;
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("InvalidRequestException", "dynamoDBv2 action payload must be valid JSON: " + e.getMessage(), 400);
+ }
+ }
+
+ private ObjectNode toDynamoDbAttribute(JsonNode value) {
+ ObjectNode attribute = objectMapper.createObjectNode();
+ if (value == null || value.isNull()) {
+ attribute.put("NULL", true);
+ } else if (value.isBoolean()) {
+ attribute.put("BOOL", value.asBoolean());
+ } else if (value.isNumber()) {
+ attribute.put("N", value.asText());
+ } else {
+ attribute.put("S", value.asText());
+ }
+ return attribute;
+ }
+
+ private String extractTopicPattern(String sql) {
+ if (sql == null) {
+ return null;
+ }
+ int from = sql.toUpperCase().indexOf(" FROM ");
+ if (from < 0) {
+ return null;
+ }
+ String tail = sql.substring(from + " FROM ".length()).trim();
+ if (tail.length() >= 2 && (tail.charAt(0) == '\'' || tail.charAt(0) == '"')) {
+ char quote = tail.charAt(0);
+ int end = tail.indexOf(quote, 1);
+ if (end > 1) {
+ return tail.substring(1, end);
+ }
+ }
+ return null;
+ }
+
+ private boolean topicMatches(String filter, String topic) {
+ if (filter == null || topic == null) {
+ return false;
+ }
+ String[] filterParts = filter.split("/", -1);
+ String[] topicParts = topic.split("/", -1);
+ int i = 0;
+ for (; i < filterParts.length; i++) {
+ String filterPart = filterParts[i];
+ if ("#".equals(filterPart)) {
+ return i == filterParts.length - 1;
+ }
+ if (i >= topicParts.length) {
+ return false;
+ }
+ if (!"+".equals(filterPart) && !filterPart.equals(topicParts[i])) {
+ return false;
+ }
+ }
+ return i == topicParts.length;
+ }
+
+ private void publishShadowUpdate(ReservedShadowTopic topic, JsonNode request, String clientToken, String region,
+ BiConsumer<String, byte[]> publisher) {
+ JsonNode previous = shadowStore.get(shadowKey(region, topic.thingName(), topic.shadowName()))
+ .map(IotShadow::getDocument)
+ .map(this::readJson)
+ .orElse(null);
+ JsonNode current = updateThingShadow(topic.thingName(), topic.shadowName(), request, region);
+ ObjectNode accepted = withClientToken(current.deepCopy(), clientToken);
+ publishJson(topic.acceptedTopic(), accepted, publisher);
+
+ ObjectNode documents = objectMapper.createObjectNode();
+ if (previous != null) {
+ documents.set("previous", previous);
+ }
+ documents.set("current", current);
+ documents.put("timestamp", Instant.now().getEpochSecond());
+ publishJson(topic.documentsTopic(), documents, publisher);
+
+ ObjectNode deltaState = objectMapper.createObjectNode();
+ JsonNode desired = current.path("state").path("desired");
+ JsonNode reported = current.path("state").path("reported");
+ if (desired.isObject()) {
+ desired.fields().forEachRemaining(entry -> {
+ JsonNode reportedValue = reported.path(entry.getKey());
+ if (reportedValue.isMissingNode() || !reportedValue.equals(entry.getValue())) {
+ deltaState.set(entry.getKey(), entry.getValue());
+ }
+ });
+ }
+ if (!deltaState.isEmpty()) {
+ ObjectNode delta = objectMapper.createObjectNode();
+ delta.set("state", deltaState);
+ delta.put("version", current.path("version").asLong());
+ delta.put("timestamp", Instant.now().getEpochSecond());
+ publishJson(topic.deltaTopic(), delta, publisher);
+ }
+ }
+
+ private void publishShadowGet(ReservedShadowTopic topic, String clientToken, String region, BiConsumer<String, byte[]> publisher) {
+ ObjectNode accepted = withClientToken(getThingShadow(topic.thingName(), topic.shadowName(), region).deepCopy(), clientToken);
+ publishJson(topic.acceptedTopic(), accepted, publisher);
+ }
+
+ private void publishShadowDelete(ReservedShadowTopic topic, String clientToken, String region, BiConsumer<String, byte[]> publisher) {
+ ObjectNode accepted = withClientToken(deleteThingShadow(topic.thingName(), topic.shadowName(), region).deepCopy(), clientToken);
+ publishJson(topic.acceptedTopic(), accepted, publisher);
+ }
+
+ private ObjectNode withClientToken(JsonNode document, String clientToken) {
+ ObjectNode node = document instanceof ObjectNode objectNode ? objectNode : objectMapper.createObjectNode();
+ if (clientToken != null && !clientToken.isBlank()) {
+ node.put("clientToken", clientToken);
+ }
+ return node;
+ }
+
+ private void publishRejected(String topic, String code, String message, String clientToken, BiConsumer<String, byte[]> publisher) {
+ ObjectNode rejected = objectMapper.createObjectNode();
+ rejected.put("code", code);
+ rejected.put("message", message == null ? code : message);
+ rejected.put("timestamp", Instant.now().getEpochSecond());
+ if (clientToken != null && !clientToken.isBlank()) {
+ rejected.put("clientToken", clientToken);
+ }
+ publishJson(topic, rejected, publisher);
+ }
+
+ private void publishJson(String topic, JsonNode payload, BiConsumer<String, byte[]> publisher) {
+ try {
+ publisher.accept(topic, objectMapper.writeValueAsBytes(payload));
+ } catch (Exception e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ }
+
+ private ReservedShadowTopic parseReservedShadowTopic(String topic) {
+ if (!topic.startsWith("$aws/things/")) {
+ return null;
+ }
+ String[] parts = topic.split("/");
+ if (parts.length == 5 && "things".equals(parts[1]) && "shadow".equals(parts[3])) {
+ return new ReservedShadowTopic(parts[2], null, parts[4]);
+ }
+ if (parts.length == 7 && "things".equals(parts[1]) && "shadow".equals(parts[3]) && "name".equals(parts[4])) {
+ return new ReservedShadowTopic(parts[2], parts[5], parts[6]);
+ }
+ return null;
+ }
+
+ private void mergeObject(ObjectNode parent, String field, JsonNode patch) {
+ if (patch == null || patch.isMissingNode()) {
+ return;
+ }
+ if (patch.isNull()) {
+ parent.remove(field);
+ return;
+ }
+ if (!patch.isObject()) {
+ return;
+ }
+ ObjectNode target = parent.withObject("/" + field);
+ patch.fields().forEachRemaining(entry -> {
+ if (entry.getValue().isNull()) {
+ target.remove(entry.getKey());
+ } else {
+ target.set(entry.getKey(), entry.getValue());
+ }
+ });
+ }
+
+ private TaggableResource taggableForArn(String resourceArn) {
+ String resource = resourceFromArn(resourceArn);
+ String region = regionFromArn(resourceArn);
+ if (resource.startsWith("thing/")) {
+ String thingName = resource.substring("thing/".length());
+ Thing thing = thingStore.get(thingKey(region, thingName))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 404));
+ return new TaggableResource(thing.getTags(), tags -> {
+ thing.setTags(tags);
+ thingStore.put(thingKey(region, thingName), thing);
+ });
+ }
+ if (resource.startsWith("cert/")) {
+ String certificateId = resource.substring("cert/".length());
+ IotCertificate certificate = describeCertificate(certificateId, region);
+ return new TaggableResource(certificate.getTags(), tags -> {
+ certificate.setTags(tags);
+ certificateStore.put(certificateKey(region, certificateId), certificate);
+ });
+ }
+ if (resource.startsWith("policy/")) {
+ String policyName = resource.substring("policy/".length());
+ IotPolicy policy = getPolicy(policyName, region);
+ return new TaggableResource(policy.getTags(), tags -> {
+ policy.setTags(tags);
+ policyStore.put(policyKey(region, policyName), policy);
+ });
+ }
+ if (resource.startsWith("rule/")) {
+ String ruleName = resource.substring("rule/".length());
+ IotTopicRule rule = getTopicRule(ruleName, region);
+ return new TaggableResource(rule.getTags(), tags -> {
+ rule.setTags(tags);
+ topicRuleStore.put(topicRuleKey(region, ruleName), rule);
+ });
+ }
+ throw new AwsException("InvalidRequestException", "Invalid resource ARN: " + resourceArn, 400);
+ }
+
+ private void validateCertificateStatus(String status) {
+ if (!Set.of("ACTIVE", "INACTIVE", "REVOKED").contains(status)) {
+ throw new AwsException("InvalidRequestException", "Unsupported certificate status: " + status, 400);
+ }
+ }
+
+ private boolean certificateHasAttachments(String certificateArn, String region) {
+ boolean policyAttached = policyAttachmentStore.scan(key -> key.startsWith("policy-attachment:" + region + ":")).stream()
+ .anyMatch(targets -> targets.contains(certificateArn));
+ boolean thingAttached = thingPrincipalStore.scan(key -> key.startsWith("thing-principal:" + region + ":")).stream()
+ .anyMatch(principals -> principals.contains(certificateArn));
+ return policyAttached || thingAttached;
+ }
+
+ private Set<String> thingNamesForJobTarget(String target, String region) {
+ String resource = target.startsWith("arn:") ? resourceFromArn(target) : target;
+ if (resource.startsWith("thing/")) {
+ String thingName = resource.substring("thing/".length());
+ describeThing(thingName, region);
+ return Set.of(thingName);
+ }
+ if (resource.startsWith("thinggroup/")) {
+ String thingGroupName = resource.substring("thinggroup/".length());
+ return listThingsInThingGroup(thingGroupName, region);
+ }
+ throw new AwsException("ResourceNotFoundException", "Unsupported or missing job target: " + target, 404);
+ }
+
+ private void updateThingTypeProperties(IotThingType type, JsonNode properties) {
+ type.setDescription(properties.path("thingTypeDescription").asText(null));
+ type.setSearchableAttributes(stringList(properties.path("searchableAttributes")));
+ }
+
+ private void updateThingGroupProperties(IotThingGroup group, JsonNode properties) {
+ group.setDescription(properties.path("thingGroupDescription").asText(null));
+ group.setAttributes(parseAttributePayload(properties.path("attributePayload")));
+ }
+
+ private List<String> stringList(JsonNode node) {
+ List<String> values = new java.util.ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(item -> values.add(item.asText()));
+ }
+ return values;
+ }
+
+ private Map<String, String> parseAttributePayload(JsonNode attributePayload) {
+ Map<String, String> attributes = new TreeMap<>();
+ JsonNode attributesNode = attributePayload.path("attributes");
+ if (attributesNode.isObject()) {
+ attributesNode.fields().forEachRemaining(entry -> attributes.put(entry.getKey(), entry.getValue().asText()));
+ }
+ return attributes;
+ }
+
+ private String blankToNull(String value) {
+ return value == null || value.isBlank() ? null : value;
+ }
+
+ private void validateJobExecutionStatus(String status) {
+ if (!Set.of("QUEUED", "IN_PROGRESS", "SUCCEEDED", "FAILED", "TIMED_OUT", "REJECTED", "REMOVED", "CANCELED").contains(status)) {
+ throw new AwsException("InvalidRequestException", "Unsupported job execution status: " + status, 400);
+ }
+ }
+
+ private String regionFromArn(String resourceArn) {
+ String[] parts = arnParts(resourceArn);
+ return parts[3];
+ }
+
+ private String resourceFromArn(String resourceArn) {
+ String[] parts = arnParts(resourceArn);
+ return parts[5];
+ }
+
+ private String[] arnParts(String resourceArn) {
+ if (resourceArn == null || resourceArn.isBlank()) {
+ throw new AwsException("InvalidRequestException", "Invalid resource ARN: " + resourceArn, 400);
+ }
+ String[] parts = resourceArn.split(":", 6);
+ if (parts.length != 6 || !"arn".equals(parts[0]) || !"iot".equals(parts[2]) || parts[3].isBlank() || parts[5].isBlank()) {
+ throw new AwsException("InvalidRequestException", "Invalid resource ARN: " + resourceArn, 400);
+ }
+ return parts;
+ }
+
+ private record ReservedShadowTopic(String thingName, String shadowName, String operation) {
+ private String baseTopic() {
+ if (shadowName != null && !shadowName.isBlank()) {
+ return "$aws/things/" + thingName + "/shadow/name/" + shadowName + "/" + operation;
+ }
+ return "$aws/things/" + thingName + "/shadow/" + operation;
+ }
+
+ private String acceptedTopic() {
+ return baseTopic() + "/accepted";
+ }
+
+ private String rejectedTopic() {
+ return baseTopic() + "/rejected";
+ }
+
+ private String documentsTopic() {
+ return updateBaseTopic() + "/documents";
+ }
+
+ private String deltaTopic() {
+ return updateBaseTopic() + "/delta";
+ }
+
+ private String updateBaseTopic() {
+ if (shadowName != null && !shadowName.isBlank()) {
+ return "$aws/things/" + thingName + "/shadow/name/" + shadowName + "/update";
+ }
+ return "$aws/things/" + thingName + "/shadow/update";
+ }
+ }
+
+ public record Page<T>(List<T> items, String nextToken) {
+ }
+
+ private record TaggableResource(Map<String, String> tags, java.util.function.Consumer<Map<String, String>> updateTags) {
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java
new file mode 100644
index 0000000000..fcebc7ee9c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java
@@ -0,0 +1,44 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.github.hectorvent.floci.core.common.TagHandler;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+
+@ApplicationScoped
+public class IotTagHandler implements TagHandler {
+
+ private final IotService iotService;
+
+ @Inject
+ public IotTagHandler(IotService iotService) {
+ this.iotService = iotService;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "iot";
+ }
+
+ @Override
+ public boolean tagsBodyIsList() {
+ return true;
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return iotService.listTagsForResource(arn);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ iotService.tagResource(arn, tags);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ iotService.untagResource(arn, tagKeys);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java
new file mode 100644
index 0000000000..5f8a03694d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java
@@ -0,0 +1,33 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class IotCertificate {
+ private String certificateId;
+ private String certificateArn;
+ private String certificatePem;
+ private String publicKey;
+ private String privateKey;
+ private String status;
+ private Instant creationDate;
+ private Map<String, String> tags = new TreeMap<>();
+
+ public String getCertificateId() { return certificateId; }
+ public void setCertificateId(String certificateId) { this.certificateId = certificateId; }
+ public String getCertificateArn() { return certificateArn; }
+ public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; }
+ public String getCertificatePem() { return certificatePem; }
+ public void setCertificatePem(String certificatePem) { this.certificatePem = certificatePem; }
+ public String getPublicKey() { return publicKey; }
+ public void setPublicKey(String publicKey) { this.publicKey = publicKey; }
+ public String getPrivateKey() { return privateKey; }
+ public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public Instant getCreationDate() { return creationDate; }
+ public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
+ 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); }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJob.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJob.java
new file mode 100644
index 0000000000..505de8088d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJob.java
@@ -0,0 +1,49 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+public class IotJob {
+
+ private String jobId;
+ private String jobArn;
+ private String document;
+ private String documentSource;
+ private String description;
+ private String targetSelection = "SNAPSHOT";
+ private String status = "IN_PROGRESS";
+ private List<String> targets = new ArrayList<>();
+ private Instant createdAt;
+ private Instant lastUpdatedAt;
+
+ public String getJobId() { return jobId; }
+ public void setJobId(String jobId) { this.jobId = jobId; }
+
+ public String getJobArn() { return jobArn; }
+ public void setJobArn(String jobArn) { this.jobArn = jobArn; }
+
+ public String getDocument() { return document; }
+ public void setDocument(String document) { this.document = document; }
+
+ public String getDocumentSource() { return documentSource; }
+ public void setDocumentSource(String documentSource) { this.documentSource = documentSource; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getTargetSelection() { return targetSelection; }
+ public void setTargetSelection(String targetSelection) { this.targetSelection = targetSelection; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public List<String> getTargets() { return targets; }
+ public void setTargets(List<String> targets) { this.targets = targets == null ? new ArrayList<>() : new ArrayList<>(targets); }
+
+ public Instant getCreatedAt() { return createdAt; }
+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+
+ public Instant getLastUpdatedAt() { return lastUpdatedAt; }
+ public void setLastUpdatedAt(Instant lastUpdatedAt) { this.lastUpdatedAt = lastUpdatedAt; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJobExecution.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJobExecution.java
new file mode 100644
index 0000000000..e4ec88e60d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotJobExecution.java
@@ -0,0 +1,49 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+
+public class IotJobExecution {
+
+ private String jobId;
+ private String thingName;
+ private String thingArn;
+ private String status = "QUEUED";
+ private Map<String, String> statusDetails = new HashMap<>();
+ private Instant queuedAt;
+ private Instant startedAt;
+ private Instant lastUpdatedAt;
+ private long executionNumber = 1L;
+ private long versionNumber = 1L;
+
+ public String getJobId() { return jobId; }
+ public void setJobId(String jobId) { this.jobId = jobId; }
+
+ public String getThingName() { return thingName; }
+ public void setThingName(String thingName) { this.thingName = thingName; }
+
+ public String getThingArn() { return thingArn; }
+ public void setThingArn(String thingArn) { this.thingArn = thingArn; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public Map<String, String> getStatusDetails() { return statusDetails; }
+ public void setStatusDetails(Map<String, String> statusDetails) { this.statusDetails = statusDetails == null ? new HashMap<>() : new HashMap<>(statusDetails); }
+
+ public Instant getQueuedAt() { return queuedAt; }
+ public void setQueuedAt(Instant queuedAt) { this.queuedAt = queuedAt; }
+
+ public Instant getStartedAt() { return startedAt; }
+ public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; }
+
+ public Instant getLastUpdatedAt() { return lastUpdatedAt; }
+ public void setLastUpdatedAt(Instant lastUpdatedAt) { this.lastUpdatedAt = lastUpdatedAt; }
+
+ public long getExecutionNumber() { return executionNumber; }
+ public void setExecutionNumber(long executionNumber) { this.executionNumber = executionNumber; }
+
+ public long getVersionNumber() { return versionNumber; }
+ public void setVersionNumber(long versionNumber) { this.versionNumber = versionNumber; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotPolicy.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotPolicy.java
new file mode 100644
index 0000000000..714940f1fb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotPolicy.java
@@ -0,0 +1,45 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class IotPolicy {
+ private String policyName;
+ private String policyArn;
+ private String policyDocument;
+ private String defaultVersionId;
+ private Instant creationDate;
+ private List<PolicyVersion> versions = new ArrayList<>();
+ private Map<String, String> tags = new TreeMap<>();
+
+ public String getPolicyName() { return policyName; }
+ public void setPolicyName(String policyName) { this.policyName = policyName; }
+ public String getPolicyArn() { return policyArn; }
+ public void setPolicyArn(String policyArn) { this.policyArn = policyArn; }
+ public String getPolicyDocument() { return policyDocument; }
+ public void setPolicyDocument(String policyDocument) { this.policyDocument = policyDocument; }
+ public String getDefaultVersionId() { return defaultVersionId; }
+ public void setDefaultVersionId(String defaultVersionId) { this.defaultVersionId = defaultVersionId; }
+ public Instant getCreationDate() { return creationDate; }
+ public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
+ public List<PolicyVersion> getVersions() { return versions == null ? List.of() : versions; }
+ public void setVersions(List<PolicyVersion> versions) { this.versions = versions == null ? new ArrayList<>() : new ArrayList<>(versions); }
+ 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); }
+
+ public static class PolicyVersion {
+ private String versionId;
+ private String document;
+ private Instant createDate;
+
+ public String getVersionId() { return versionId; }
+ public void setVersionId(String versionId) { this.versionId = versionId; }
+ public String getDocument() { return document; }
+ public void setDocument(String document) { this.document = document; }
+ public Instant getCreateDate() { return createDate; }
+ public void setCreateDate(Instant createDate) { this.createDate = createDate; }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotRetainedMessage.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotRetainedMessage.java
new file mode 100644
index 0000000000..ed594b7bba
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotRetainedMessage.java
@@ -0,0 +1,19 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+
+public class IotRetainedMessage {
+ private String topic;
+ private String payload;
+ private int qos;
+ private Instant lastModifiedTime;
+
+ public String getTopic() { return topic; }
+ public void setTopic(String topic) { this.topic = topic; }
+ public String getPayload() { return payload; }
+ public void setPayload(String payload) { this.payload = payload; }
+ public int getQos() { return qos; }
+ public void setQos(int qos) { this.qos = qos; }
+ public Instant getLastModifiedTime() { return lastModifiedTime; }
+ public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotShadow.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotShadow.java
new file mode 100644
index 0000000000..b59f051c9c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotShadow.java
@@ -0,0 +1,17 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+public class IotShadow {
+ private String thingName;
+ private String shadowName;
+ private String document;
+ private long version;
+
+ public String getThingName() { return thingName; }
+ public void setThingName(String thingName) { this.thingName = thingName; }
+ public String getShadowName() { return shadowName; }
+ public void setShadowName(String shadowName) { this.shadowName = shadowName; }
+ public String getDocument() { return document; }
+ public void setDocument(String document) { this.document = document; }
+ public long getVersion() { return version; }
+ public void setVersion(long version) { this.version = version; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingGroup.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingGroup.java
new file mode 100644
index 0000000000..d6b837733b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingGroup.java
@@ -0,0 +1,37 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+
+public class IotThingGroup {
+
+ private String thingGroupName;
+ private String thingGroupArn;
+ private String thingGroupId;
+ private String description;
+ private Map<String, String> attributes = new HashMap<>();
+ private long version = 1L;
+ private Instant creationDate;
+
+ public String getThingGroupName() { return thingGroupName; }
+ public void setThingGroupName(String thingGroupName) { this.thingGroupName = thingGroupName; }
+
+ public String getThingGroupArn() { return thingGroupArn; }
+ public void setThingGroupArn(String thingGroupArn) { this.thingGroupArn = thingGroupArn; }
+
+ public String getThingGroupId() { return thingGroupId; }
+ public void setThingGroupId(String thingGroupId) { this.thingGroupId = thingGroupId; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public Map<String, String> getAttributes() { return attributes; }
+ public void setAttributes(Map<String, String> attributes) { this.attributes = attributes == null ? new HashMap<>() : new HashMap<>(attributes); }
+
+ public long getVersion() { return version; }
+ public void setVersion(long version) { this.version = version; }
+
+ public Instant getCreationDate() { return creationDate; }
+ public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingType.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingType.java
new file mode 100644
index 0000000000..45766009e0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotThingType.java
@@ -0,0 +1,41 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+public class IotThingType {
+
+ private String thingTypeName;
+ private String thingTypeArn;
+ private String thingTypeId;
+ private String description;
+ private List<String> searchableAttributes = new ArrayList<>();
+ private boolean deprecated;
+ private Instant creationDate;
+ private Instant deprecatedDate;
+
+ public String getThingTypeName() { return thingTypeName; }
+ public void setThingTypeName(String thingTypeName) { this.thingTypeName = thingTypeName; }
+
+ public String getThingTypeArn() { return thingTypeArn; }
+ public void setThingTypeArn(String thingTypeArn) { this.thingTypeArn = thingTypeArn; }
+
+ public String getThingTypeId() { return thingTypeId; }
+ public void setThingTypeId(String thingTypeId) { this.thingTypeId = thingTypeId; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public List<String> getSearchableAttributes() { return searchableAttributes; }
+ public void setSearchableAttributes(List<String> searchableAttributes) { this.searchableAttributes = searchableAttributes == null ? new ArrayList<>() : new ArrayList<>(searchableAttributes); }
+
+ public boolean isDeprecated() { return deprecated; }
+ public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; }
+
+ public Instant getCreationDate() { return creationDate; }
+ public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
+
+ public Instant getDeprecatedDate() { return deprecatedDate; }
+ public void setDeprecatedDate(Instant deprecatedDate) { this.deprecatedDate = deprecatedDate; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java
new file mode 100644
index 0000000000..0512ca5f71
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java
@@ -0,0 +1,80 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class IotTopicRule {
+ private String ruleName;
+ private String ruleArn;
+ private String sql;
+ private String description;
+ private boolean ruleDisabled;
+ private String actionsJson = "[]";
+ private Instant createdAt;
+ private Map<String, String> tags = new TreeMap<>();
+
+ public String getRuleName() {
+ return ruleName;
+ }
+
+ public void setRuleName(String ruleName) {
+ this.ruleName = ruleName;
+ }
+
+ public String getRuleArn() {
+ return ruleArn;
+ }
+
+ public void setRuleArn(String ruleArn) {
+ this.ruleArn = ruleArn;
+ }
+
+ public String getSql() {
+ return sql;
+ }
+
+ public void setSql(String sql) {
+ this.sql = sql;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public boolean isRuleDisabled() {
+ return ruleDisabled;
+ }
+
+ public void setRuleDisabled(boolean ruleDisabled) {
+ this.ruleDisabled = ruleDisabled;
+ }
+
+ public String getActionsJson() {
+ return actionsJson;
+ }
+
+ public void setActionsJson(String actionsJson) {
+ this.actionsJson = actionsJson;
+ }
+
+ public Instant getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(Instant createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ 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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/Thing.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/Thing.java
new file mode 100644
index 0000000000..9cae2f8c17
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/Thing.java
@@ -0,0 +1,90 @@
+package io.github.hectorvent.floci.services.iot.model;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Thing {
+
+ private String thingName;
+ private String thingArn;
+ private String thingId;
+ private String thingTypeName;
+ private Map<String, String> attributes = new HashMap<>();
+ private Map<String, String> tags = new HashMap<>();
+ private long version;
+ private Instant creationDate;
+ private Instant lastModifiedDate;
+
+ public String getThingName() {
+ return thingName;
+ }
+
+ public void setThingName(String thingName) {
+ this.thingName = thingName;
+ }
+
+ public String getThingArn() {
+ return thingArn;
+ }
+
+ public void setThingArn(String thingArn) {
+ this.thingArn = thingArn;
+ }
+
+ public String getThingId() {
+ return thingId;
+ }
+
+ public void setThingId(String thingId) {
+ this.thingId = thingId;
+ }
+
+ public String getThingTypeName() {
+ return thingTypeName;
+ }
+
+ public void setThingTypeName(String thingTypeName) {
+ this.thingTypeName = thingTypeName;
+ }
+
+ public Map<String, String> getAttributes() {
+ return attributes;
+ }
+
+ public void setAttributes(Map<String, String> attributes) {
+ this.attributes = attributes != null ? new HashMap<>(attributes) : new HashMap<>();
+ }
+
+ public Map<String, String> getTags() {
+ return tags;
+ }
+
+ public void setTags(Map<String, String> tags) {
+ this.tags = tags != null ? new HashMap<>(tags) : new HashMap<>();
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ public void setVersion(long version) {
+ this.version = version;
+ }
+
+ public Instant getCreationDate() {
+ return creationDate;
+ }
+
+ public void setCreationDate(Instant creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public Instant getLastModifiedDate() {
+ return lastModifiedDate;
+ }
+
+ public void setLastModifiedDate(Instant lastModifiedDate) {
+ this.lastModifiedDate = lastModifiedDate;
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 54543c012d..087c80bf14 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -383,3 +383,12 @@ floci:
enabled: true
s3vectors:
enabled: true
+ iot:
+ enabled: true
+ mqtt:
+ enabled: true
+ auto-start: false
+ host: 0.0.0.0
+ port: 1883
+ iotdata:
+ enabled: true
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDataIntegrationTest.java
new file mode 100644
index 0000000000..362709c99e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDataIntegrationTest.java
@@ -0,0 +1,208 @@
+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.nullValue;
+
+@QuarkusTest
+class IotDataIntegrationTest {
+
+ @Test
+ void classicShadowLifecycle() {
+ given()
+ .when()
+ .get("/things/phase-five-thing/shadow")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+
+ given()
+ .contentType("application/json")
+ .body("{\"state\":{\"desired\":{\"color\":\"blue\"}}}")
+ .when()
+ .post("/things/phase-five-thing/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.color", equalTo("blue"))
+ .body("version", equalTo(1));
+
+ given()
+ .contentType("application/json")
+ .body("{\"state\":{\"reported\":{\"color\":\"green\"}}}")
+ .when()
+ .post("/things/phase-five-thing/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.color", equalTo("blue"))
+ .body("state.reported.color", equalTo("green"))
+ .body("version", equalTo(2));
+
+ given()
+ .when()
+ .delete("/things/phase-five-thing/shadow")
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(2));
+
+ given()
+ .when()
+ .get("/things/phase-five-thing/shadow")
+ .then()
+ .statusCode(404);
+ }
+
+ @Test
+ void namedShadowLifecycleAndPublish() {
+ given()
+ .contentType("application/json")
+ .queryParam("name", "settings")
+ .body("{\"state\":{\"desired\":{\"mode\":\"auto\"}}}")
+ .when()
+ .post("/things/phase-five-named/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.mode", equalTo("auto"));
+
+ given()
+ .when()
+ .get("/api/things/shadow/ListNamedShadowsForThing/phase-five-named")
+ .then()
+ .statusCode(200)
+ .body("results", hasItem("settings"));
+
+ given()
+ .queryParam("name", "settings")
+ .when()
+ .get("/things/phase-five-named/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.mode", equalTo("auto"));
+
+ given()
+ .contentType("text/plain")
+ .body("payload")
+ .when()
+ .post("/topics/devices/phase-five-named/events")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("name", "settings")
+ .when()
+ .delete("/things/phase-five-named/shadow")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ void retainedMessagesRoundTripAndDeleteWithEmptyRetainedPublish() {
+ given()
+ .contentType("text/plain")
+ .queryParam("retain", true)
+ .queryParam("qos", 1)
+ .body("retained-payload")
+ .when()
+ .post("/topics/devices/mvp1/retained")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/retainedMessage/devices/mvp1/retained")
+ .then()
+ .statusCode(200)
+ .body("topic", equalTo("devices/mvp1/retained"))
+ .body("payload", equalTo("cmV0YWluZWQtcGF5bG9hZA=="))
+ .body("qos", equalTo(1));
+
+ given()
+ .contentType("text/plain")
+ .queryParam("retain", true)
+ .body("other")
+ .when()
+ .post("/topics/devices/mvp1/retained-other")
+ .then()
+ .statusCode(200);
+
+ String nextToken = given()
+ .queryParam("maxResults", 1)
+ .when()
+ .get("/retainedMessage")
+ .then()
+ .statusCode(200)
+ .body("retainedTopics.size()", equalTo(1))
+ .extract()
+ .path("nextToken");
+
+ given()
+ .queryParam("maxResults", 1)
+ .queryParam("nextToken", nextToken)
+ .when()
+ .get("/retainedMessage")
+ .then()
+ .statusCode(200)
+ .body("retainedTopics.size()", equalTo(1));
+
+ given()
+ .contentType("application/octet-stream")
+ .queryParam("retain", true)
+ .body(new byte[0])
+ .when()
+ .post("/topics/devices/mvp1/retained")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/retainedMessage/devices/mvp1/retained")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ void shadowNullDeletesPropertiesAndVersionConflicts() {
+ given()
+ .contentType("application/json")
+ .body("{\"state\":{\"desired\":{\"color\":\"blue\",\"mode\":\"auto\"}}}")
+ .when()
+ .post("/things/mvp1-shadow/shadow")
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(1));
+
+ given()
+ .contentType("application/json")
+ .body("{\"version\":1,\"state\":{\"desired\":{\"color\":null}}}")
+ .when()
+ .post("/things/mvp1-shadow/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.color", nullValue())
+ .body("state.desired.mode", equalTo("auto"))
+ .body("version", equalTo(2));
+
+ given()
+ .contentType("application/json")
+ .body("{\"version\":1,\"state\":{\"desired\":{\"mode\":\"manual\"}}}")
+ .when()
+ .post("/things/mvp1-shadow/shadow")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("VersionConflictException"));
+
+ given()
+ .contentType("application/json")
+ .body("{\"version\":2,\"state\":{\"desired\":null}}")
+ .when()
+ .post("/things/mvp1-shadow/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired", nullValue())
+ .body("version", equalTo(3));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotEndpointHostnameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotEndpointHostnameIntegrationTest.java
new file mode 100644
index 0000000000..afcbc8ff60
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotEndpointHostnameIntegrationTest.java
@@ -0,0 +1,33 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+@TestProfile(IotEndpointHostnameIntegrationTest.HostnameProfile.class)
+class IotEndpointHostnameIntegrationTest {
+
+ @Test
+ void configuredHostnameIsUsedInDescribeEndpoint() {
+ given()
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200)
+ .body("endpointAddress", equalTo("floci:4566"));
+ }
+
+ public static class HostnameProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.hostname", "floci");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
new file mode 100644
index 0000000000..ad8a466e3c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
@@ -0,0 +1,763 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+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.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class IotIntegrationTest {
+
+ @Test
+ @Order(1)
+ void unsupportedEndpointTypeReturnsAwsError() {
+ given()
+ .queryParam("endpointType", "unsupported")
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+ }
+
+ @Test
+ @Order(2)
+ void defaultDescribeEndpointReturnsBaseUrlAuthority() {
+ given()
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200)
+ .body("endpointAddress", equalTo("localhost:4566"));
+ }
+
+ @Test
+ @Order(3)
+ void describeEndpointAcceptsAwsDefaultEndpointType() {
+ given()
+ .queryParam("endpointType", "iot:Data-ATS")
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200)
+ .body("endpointAddress", equalTo("localhost:4566"));
+ }
+
+ @Test
+ @Order(4)
+ void describeMissingThingReturnsAwsError() {
+ given()
+ .when()
+ .get("/things/missing-thing")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ @Order(5)
+ void createThingReturnsAwsShape() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "attributePayload": {
+ "attributes": {
+ "env": "test"
+ }
+ }
+ }
+ """)
+ .when()
+ .post("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("thingName", equalTo("phase-two-thing"))
+ .body("thingArn", containsString(":iot:us-east-1:000000000000:thing/phase-two-thing"))
+ .body("thingId", notNullValue())
+ .body("version", equalTo(1))
+ .body("attributes.env", equalTo("test"));
+ }
+
+ @Test
+ @Order(6)
+ void identicalCreateThingIsIdempotent() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "attributePayload": {
+ "attributes": {
+ "env": "test"
+ }
+ }
+ }
+ """)
+ .when()
+ .post("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("thingName", equalTo("phase-two-thing"))
+ .body("attributes.env", equalTo("test"));
+ }
+
+ @Test
+ @Order(7)
+ void duplicateCreateThingReturnsConflict() {
+ given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/phase-two-thing")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("ResourceAlreadyExistsException"));
+ }
+
+ @Test
+ @Order(8)
+ void describeThingReturnsStoredThing() {
+ given()
+ .when()
+ .get("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("thingName", equalTo("phase-two-thing"))
+ .body("attributes.env", equalTo("test"))
+ .body("creationDate", notNullValue())
+ .body("lastModifiedDate", notNullValue());
+ }
+
+ @Test
+ @Order(9)
+ void listThingsIncludesCreatedThing() {
+ given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/phase-two-other")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/things")
+ .then()
+ .statusCode(200)
+ .body("things.thingName", hasItem("phase-two-thing"))
+ .body("things.thingName", hasItem("phase-two-other"));
+
+ String nextToken = given()
+ .queryParam("maxResults", 1)
+ .when()
+ .get("/things")
+ .then()
+ .statusCode(200)
+ .body("things.size()", equalTo(1))
+ .body("nextToken", notNullValue())
+ .extract()
+ .path("nextToken");
+
+ given()
+ .queryParam("maxResults", 1)
+ .queryParam("nextToken", nextToken)
+ .when()
+ .get("/things")
+ .then()
+ .statusCode(200)
+ .body("things.size()", equalTo(1));
+ }
+
+ @Test
+ @Order(10)
+ void updateThingChangesAttributes() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "attributePayload": {
+ "attributes": {
+ "env": "updated",
+ "owner": "iot"
+ }
+ }
+ }
+ """)
+ .when()
+ .patch("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(2));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "expectedVersion": 2,
+ "attributePayload": {
+ "attributes": {
+ "env": "versioned",
+ "owner": "iot"
+ }
+ }
+ }
+ """)
+ .when()
+ .patch("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(3));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "expectedVersion": 2,
+ "attributePayload": {
+ "attributes": {
+ "env": "stale"
+ }
+ }
+ }
+ """)
+ .when()
+ .patch("/things/phase-two-thing")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("VersionConflictException"));
+
+ given()
+ .when()
+ .get("/things/phase-two-thing")
+ .then()
+ .statusCode(200)
+ .body("attributes.env", equalTo("versioned"))
+ .body("attributes.owner", equalTo("iot"));
+ }
+
+ @Test
+ @Order(11)
+ void deleteThingRemovesThing() {
+ given()
+ .when()
+ .delete("/things/phase-two-thing")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/things/phase-two-thing")
+ .then()
+ .statusCode(404);
+
+ given()
+ .when()
+ .get("/things")
+ .then()
+ .statusCode(200)
+ .body("things.thingName", not(hasItem("phase-two-thing")))
+ .body("things.thingName", hasItem("phase-two-other"));
+ }
+
+ @Test
+ @Order(12)
+ void listTagsForUntaggedThingReturnsEmptyList() {
+ String thingArn = createThingAndReturnArn("phase-three-untagged");
+
+ given()
+ .queryParam("resourceArn", thingArn)
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(200)
+ .body("tags.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(13)
+ void tagResourceAddsThingTags() {
+ String thingArn = createThingAndReturnArn("phase-three-tagged");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "%s",
+ "tags": [
+ {"Key": "env", "Value": "test"},
+ {"Key": "owner", "Value": "iot"}
+ ]
+ }
+ """.formatted(thingArn))
+ .when()
+ .post("/tags")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("resourceArn", thingArn)
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(200)
+ .body("tags.Key", hasItem("env"))
+ .body("tags.Value", hasItem("test"))
+ .body("tags.Key", hasItem("owner"))
+ .body("tags.Value", hasItem("iot"));
+ }
+
+ @Test
+ @Order(14)
+ void untagResourceRemovesSelectedThingTags() {
+ String thingArn = createThingAndReturnArn("phase-three-untag");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "%s",
+ "tags": [
+ {"Key": "env", "Value": "test"},
+ {"Key": "owner", "Value": "iot"}
+ ]
+ }
+ """.formatted(thingArn))
+ .when()
+ .post("/tags")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "%s",
+ "tagKeys": ["env"]
+ }
+ """.formatted(thingArn))
+ .when()
+ .post("/untag")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("resourceArn", thingArn)
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(200)
+ .body("tags.Key", not(hasItem("env")))
+ .body("tags.Key", hasItem("owner"));
+ }
+
+ @Test
+ @Order(15)
+ void taggingMissingThingReturnsAwsError() {
+ String missingThingArn = "arn:aws:iot:us-east-1:000000000000:thing/phase-three-missing";
+
+ given()
+ .queryParam("resourceArn", missingThingArn)
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ @Order(16)
+ void certificatesPoliciesAndAttachmentsRoundTrip() {
+ String certificateArn = given()
+ .contentType("application/json")
+ .queryParam("setAsActive", true)
+ .body("{}")
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .body("certificateId", notNullValue())
+ .body("certificateArn", containsString(":iot:us-east-1:000000000000:cert/"))
+ .body("certificatePem", containsString("BEGIN CERTIFICATE"))
+ .body("keyPair.PublicKey", containsString("BEGIN PUBLIC KEY"))
+ .body("keyPair.PrivateKey", containsString("BEGIN PRIVATE KEY"))
+ .extract()
+ .path("certificateArn");
+ String certificateId = certificateArn.substring(certificateArn.lastIndexOf('/') + 1);
+
+ given()
+ .when()
+ .get("/certificates/" + certificateId)
+ .then()
+ .statusCode(200)
+ .body("certificateDescription.status", equalTo("ACTIVE"))
+ .body("certificateDescription.certificateArn", equalTo(certificateArn));
+
+ given()
+ .when()
+ .get("/certificates")
+ .then()
+ .statusCode(200)
+ .body("certificates.certificateArn", hasItem(certificateArn));
+
+ given()
+ .contentType("application/json")
+ .body("{\"newStatus\":\"INACTIVE\"}")
+ .when()
+ .put("/certificates/" + certificateId)
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/certificates/" + certificateId)
+ .then()
+ .statusCode(200)
+ .body("certificateDescription.status", equalTo("INACTIVE"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "policyDocument": "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}"
+ }
+ """)
+ .when()
+ .post("/policies/phase-four-policy")
+ .then()
+ .statusCode(200)
+ .body("policyName", equalTo("phase-four-policy"));
+
+ given()
+ .when()
+ .get("/policies/phase-four-policy")
+ .then()
+ .statusCode(200)
+ .body("policyName", equalTo("phase-four-policy"))
+ .body("policyDocument", containsString("2012-10-17"));
+
+ given()
+ .when()
+ .get("/policies")
+ .then()
+ .statusCode(200)
+ .body("policies.policyName", hasItem("phase-four-policy"));
+
+ given()
+ .queryParam("target", certificateArn)
+ .when()
+ .put("/target-policies/phase-four-policy")
+ .then()
+ .statusCode(200);
+
+ String thingArn = createThingAndReturnArn("phase-four-principal-thing");
+ given()
+ .queryParam("principal", certificateArn)
+ .when()
+ .put("/things/phase-four-principal-thing/principals")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/things/phase-four-principal-thing/principals")
+ .then()
+ .statusCode(200)
+ .body("principals", hasItem(certificateArn));
+
+ given()
+ .queryParam("principal", certificateArn)
+ .when()
+ .delete("/things/phase-four-principal-thing/principals")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("target", certificateArn)
+ .when()
+ .post("/target-policies/phase-four-policy")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(17)
+ void certificateDeleteCsrStatusAndTagsMatchMvpLifecycle() {
+ String activeArn = given()
+ .queryParam("setAsActive", true)
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("certificateArn");
+ String activeId = activeArn.substring(activeArn.lastIndexOf('/') + 1);
+
+ given()
+ .when()
+ .delete("/certificates/" + activeId)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+
+ given()
+ .contentType("application/json")
+ .body("{\"newStatus\":\"PENDING_TRANSFER\"}")
+ .when()
+ .put("/certificates/" + activeId)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+
+ given()
+ .contentType("application/json")
+ .body("{\"newStatus\":\"INACTIVE\"}")
+ .when()
+ .put("/certificates/" + activeId)
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "%s",
+ "tags": [{"Key": "env", "Value": "cert"}]
+ }
+ """.formatted(activeArn))
+ .when()
+ .post("/tags")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("resourceArn", activeArn)
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(200)
+ .body("tags.Key", hasItem("env"))
+ .body("tags.Value", hasItem("cert"));
+
+ given()
+ .when()
+ .delete("/certificates/" + activeId)
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/certificates/" + activeId)
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+
+ String csrArn = given()
+ .contentType("application/json")
+ .queryParam("setAsActive", false)
+ .body("{\"certificateSigningRequest\":\"-----BEGIN CERTIFICATE REQUEST-----\\nfloci\\n-----END CERTIFICATE REQUEST-----\"}")
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(200)
+ .body("certificatePem", containsString("BEGIN CERTIFICATE"))
+ .extract()
+ .path("certificateArn");
+ String csrId = csrArn.substring(csrArn.lastIndexOf('/') + 1);
+
+ given()
+ .when()
+ .delete("/certificates/" + csrId)
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(18)
+ void certificateDeleteRejectsThingPrincipalAttachment() {
+ String certificateArn = given()
+ .queryParam("setAsActive", false)
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("certificateArn");
+ String certificateId = certificateArn.substring(certificateArn.lastIndexOf('/') + 1);
+
+ createThingAndReturnArn("mvp1-attached-cert-thing");
+ given()
+ .queryParam("principal", certificateArn)
+ .when()
+ .put("/things/mvp1-attached-cert-thing/principals")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .delete("/certificates/" + certificateId)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+
+ given()
+ .queryParam("principal", certificateArn)
+ .when()
+ .get("/principals/things")
+ .then()
+ .statusCode(200)
+ .body("things", hasItem("mvp1-attached-cert-thing"));
+ }
+
+ @Test
+ @Order(19)
+ void policyCrudVersionsAttachmentReadsAndTagsMatchMvpLifecycle() {
+ given()
+ .contentType("application/json")
+ .body("{\"policyDocument\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}\"}")
+ .when()
+ .post("/policies/phase-four-policy")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("ResourceAlreadyExistsException"));
+
+ String policyArn = given()
+ .contentType("application/json")
+ .body("{\"policyDocument\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}\"}")
+ .when()
+ .post("/policies/mvp1-policy")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("policyArn");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "%s",
+ "tags": [{"Key": "env", "Value": "policy"}]
+ }
+ """.formatted(policyArn))
+ .when()
+ .post("/tags")
+ .then()
+ .statusCode(200);
+
+ String versionId = given()
+ .contentType("application/json")
+ .queryParam("setAsDefault", true)
+ .body("{\"policyDocument\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\"}]}\"}")
+ .when()
+ .post("/policies/mvp1-policy/version")
+ .then()
+ .statusCode(200)
+ .body("isDefaultVersion", equalTo(true))
+ .extract()
+ .path("policyVersionId");
+
+ given()
+ .when()
+ .get("/policies/mvp1-policy/version")
+ .then()
+ .statusCode(200)
+ .body("policyVersions.versionId", hasItem(versionId));
+
+ given()
+ .when()
+ .get("/policies/mvp1-policy/version/" + versionId)
+ .then()
+ .statusCode(200)
+ .body("policyDocument", containsString("Allow"));
+
+ given()
+ .when()
+ .patch("/policies/mvp1-policy/version/1")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .delete("/policies/mvp1-policy/version/" + versionId)
+ .then()
+ .statusCode(200);
+
+ String certificateArn = given()
+ .queryParam("setAsActive", false)
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("certificateArn");
+
+ given()
+ .queryParam("target", certificateArn)
+ .when()
+ .put("/target-policies/mvp1-policy")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/attached-policies/" + certificateArn)
+ .then()
+ .statusCode(200)
+ .body("policies.policyName", hasItem("mvp1-policy"));
+
+ given()
+ .when()
+ .get("/policy-targets/mvp1-policy")
+ .then()
+ .statusCode(200)
+ .body("targets", hasItem(certificateArn));
+
+ given()
+ .when()
+ .delete("/policies/mvp1-policy")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+
+ given()
+ .queryParam("target", certificateArn)
+ .when()
+ .post("/target-policies/mvp1-policy")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .delete("/policies/mvp1-policy")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/policies/mvp1-policy")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ private String createThingAndReturnArn(String thingName) {
+ return given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/" + thingName)
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("thingArn");
+ }
+
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotJobsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotJobsIntegrationTest.java
new file mode 100644
index 0000000000..e65c2e2c4b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotJobsIntegrationTest.java
@@ -0,0 +1,145 @@
+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.notNullValue;
+
+@QuarkusTest
+class IotJobsIntegrationTest {
+
+ @Test
+ void jobControlPlaneCreatesJobAndMaterializesThingExecution() {
+ String thingArn = given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/mvp2-job-thing")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("thingArn");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "targets": ["%s"],
+ "document": "{\\"operation\\":\\"reboot\\"}",
+ "description": "mvp2 job",
+ "targetSelection": "SNAPSHOT"
+ }
+ """.formatted(thingArn))
+ .when()
+ .put("/jobs/mvp2-job")
+ .then()
+ .statusCode(200)
+ .body("jobId", equalTo("mvp2-job"))
+ .body("jobArn", notNullValue())
+ .body("description", equalTo("mvp2 job"));
+
+ given()
+ .when()
+ .get("/jobs/mvp2-job")
+ .then()
+ .statusCode(200)
+ .body("job.jobId", equalTo("mvp2-job"))
+ .body("job.status", equalTo("IN_PROGRESS"))
+ .body("job.targets", hasItem(thingArn));
+
+ given()
+ .when()
+ .get("/jobs")
+ .then()
+ .statusCode(200)
+ .body("jobs.jobId", hasItem("mvp2-job"));
+
+ given()
+ .when()
+ .get("/things/mvp2-job-thing/jobs")
+ .then()
+ .statusCode(200)
+ .body("executionSummaries.jobId", hasItem("mvp2-job"));
+ }
+
+ @Test
+ void jobsDataPlaneStartsAndUpdatesPendingExecution() {
+ String thingArn = given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/mvp2-jobs-data-thing")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("thingArn");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "targets": ["%s"],
+ "document": "{\\"operation\\":\\"rotate\\"}"
+ }
+ """.formatted(thingArn))
+ .when()
+ .put("/jobs/mvp2-jobs-data-job")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("endpointType", "iot:Jobs")
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200)
+ .body("endpointAddress", notNullValue());
+
+ given()
+ .when()
+ .get("/things/mvp2-jobs-data-thing/jobs")
+ .then()
+ .statusCode(200)
+ .body("queuedJobs.jobId", hasItem("mvp2-jobs-data-job"));
+
+ given()
+ .contentType("application/json")
+ .body("{\"statusDetails\":{\"phase\":\"download\"}}")
+ .when()
+ .put("/things/mvp2-jobs-data-thing/jobs/$next")
+ .then()
+ .statusCode(200)
+ .body("execution.jobId", equalTo("mvp2-jobs-data-job"))
+ .body("execution.status", equalTo("IN_PROGRESS"))
+ .body("execution.statusDetails.phase", equalTo("download"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "status": "SUCCEEDED",
+ "expectedVersion": 2,
+ "includeJobExecutionState": true,
+ "includeJobDocument": true
+ }
+ """)
+ .when()
+ .post("/things/mvp2-jobs-data-thing/jobs/mvp2-jobs-data-job")
+ .then()
+ .statusCode(200)
+ .body("executionState.status", equalTo("SUCCEEDED"))
+ .body("executionState.versionNumber", equalTo(3))
+ .body("jobDocument", equalTo("{\"operation\":\"rotate\"}"));
+
+ given()
+ .when()
+ .get("/things/mvp2-jobs-data-thing/jobs/mvp2-jobs-data-job")
+ .then()
+ .statusCode(200)
+ .body("execution.status", equalTo("SUCCEEDED"))
+ .body("execution.versionNumber", equalTo(3));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttDisabledIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttDisabledIntegrationTest.java
new file mode 100644
index 0000000000..ee1cd8bc9a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttDisabledIntegrationTest.java
@@ -0,0 +1,39 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@QuarkusTest
+@TestProfile(IotMqttDisabledIntegrationTest.DisabledMqttProfile.class)
+class IotMqttDisabledIntegrationTest {
+
+ private static final int PORT = 18830;
+
+ @Test
+ void disabledMqttDoesNotOpenConfiguredPort() {
+ assertThrows(Exception.class, () -> {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", PORT), 250);
+ }
+ });
+ }
+
+ public static final class DisabledMqttProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of(
+ "floci.services.iot.mqtt.enabled", "false",
+ "floci.services.iot.mqtt.host", "127.0.0.1",
+ "floci.services.iot.mqtt.port", Integer.toString(PORT)
+ );
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java
new file mode 100644
index 0000000000..297b0205b5
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java
@@ -0,0 +1,571 @@
+package io.github.hectorvent.floci.services.iot;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
+import org.eclipse.paho.client.mqttv3.MqttCallback;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttException;
+import org.eclipse.paho.client.mqttv3.MqttMessage;
+import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+@TestProfile(IotMqttEnabledIntegrationTest.EnabledMqttProfile.class)
+class IotMqttEnabledIntegrationTest {
+
+ private static final int PORT = 18831;
+ private static final String BROKER_URI = "tcp://127.0.0.1:" + PORT;
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @Inject
+ IotPublishEventRecorder eventRecorder;
+
+ @BeforeEach
+ void clearEvents() {
+ eventRecorder.clear();
+ }
+
+ @Test
+ void enabledMqttAcceptsConnect() throws Exception {
+ try (MqttTestClient client = connectMqtt("phase6-connect")) {
+ assertTrue(client.isConnected());
+ }
+ }
+
+ @Test
+ void enabledMqttAcceptsMqtt5Connect() throws Exception {
+ try (Mqtt5TestClient client = connectMqtt5("phase6-connect-v5")) {
+ assertTrue(client.isConnected());
+ }
+ }
+
+ @Test
+ void deleteConnectionClosesConnectedMqttClient() throws Exception {
+ String clientId = "phase6-delete-" + System.nanoTime();
+
+ try (MqttTestClient client = connectMqttClientId(clientId)) {
+ given()
+ .queryParam("cleanSession", true)
+ .when()
+ .delete("/connections/{clientId}", clientId)
+ .then()
+ .statusCode(200);
+
+ client.awaitDisconnected();
+ }
+
+ given()
+ .when()
+ .delete("/connections/{clientId}", clientId)
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ void connectionApisReturnLiveMqttStateAndSendDirectMessage() throws Exception {
+ String clientId = "phase6-connection-" + System.nanoTime();
+ String topic = "phase6/direct/" + System.nanoTime();
+ byte[] payload = "direct-payload".getBytes(StandardCharsets.UTF_8);
+
+ try (MqttTestClient client = connectMqttClientId(clientId)) {
+ client.subscribe(topic);
+
+ given()
+ .queryParam("includeSocketInformation", true)
+ .when()
+ .get("/connections/{clientId}", clientId)
+ .then()
+ .statusCode(200)
+ .body("clientId", equalTo(clientId))
+ .body("connected", equalTo(true))
+ .body("cleanSession", equalTo(true))
+ .body("sourceIp", equalTo("127.0.0.1"));
+
+ given()
+ .when()
+ .get("/connections/{clientId}/subscriptions", clientId)
+ .then()
+ .statusCode(200)
+ .body("subscriptions[0].topicFilter", equalTo(topic))
+ .body("subscriptions[0].qos", equalTo(0));
+
+ given()
+ .queryParam("topic", topic)
+ .body(payload)
+ .when()
+ .post("/connections/{clientId}/messages", clientId)
+ .then()
+ .statusCode(200)
+ .body("message", equalTo("OK"));
+
+ MqttPublish received = client.takePublish();
+ assertEquals(topic, received.topic());
+ assertArrayEquals(payload, received.payload());
+ }
+
+ given()
+ .when()
+ .get("/connections/{clientId}", clientId)
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ void mqttPublishEmitsEventAndDeliversToSubscriber() throws Exception {
+ String topic = "phase6/devices/one/events";
+ byte[] payload = "hello-phase-six".getBytes(StandardCharsets.UTF_8);
+
+ try (MqttTestClient subscriber = connectMqtt("phase6-sub")) {
+ subscriber.subscribe(topic);
+
+ try (MqttTestClient publisher = connectMqtt("phase6-pub")) {
+ publisher.publish(topic, payload);
+ }
+
+ MqttPublish received = subscriber.takePublish();
+ assertEquals(topic, received.topic());
+ assertArrayEquals(payload, received.payload());
+ }
+
+ awaitPublishedEvent(topic, payload);
+ }
+
+ @Test
+ void mqttQos1PublishIsAcknowledgedAndDelivered() throws Exception {
+ String topic = "phase6/devices/qos1/events";
+ byte[] payload = "hello-qos-one".getBytes(StandardCharsets.UTF_8);
+
+ try (MqttTestClient subscriber = connectMqtt("phase6-qos1-sub")) {
+ subscriber.subscribe(topic, 1);
+
+ try (MqttTestClient publisher = connectMqtt("phase6-qos1-pub")) {
+ publisher.publish(topic, payload, 1);
+ }
+
+ MqttPublish received = subscriber.takePublish();
+ assertEquals(topic, received.topic());
+ assertArrayEquals(payload, received.payload());
+ }
+
+ awaitPublishedEvent(topic, payload);
+ }
+
+ @Test
+ void shadowUpdateTopicPublishesAcceptedResponse() throws Exception {
+ try (MqttTestClient subscriber = connectMqtt("phase7-update-sub")) {
+ subscriber.subscribe("$aws/things/phase7Thing/shadow/update/accepted");
+
+ try (MqttTestClient publisher = connectMqtt("phase7-update-pub")) {
+ publisher.publish("$aws/things/phase7Thing/shadow/update",
+ json("{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"token-1\"}"));
+ }
+
+ MqttPublish accepted = subscriber.takePublish();
+ JsonNode payload = readJson(accepted.payload());
+ assertEquals("$aws/things/phase7Thing/shadow/update/accepted", accepted.topic());
+ assertEquals("blue", payload.path("state").path("desired").path("color").asText());
+ assertEquals("token-1", payload.path("clientToken").asText());
+ }
+ }
+
+ @Test
+ void mqtt5ShadowUpdateTopicPublishesAcceptedResponse() throws Exception {
+ try (Mqtt5TestClient subscriber = connectMqtt5("phase7-mqtt5-update-sub")) {
+ subscriber.subscribe("$aws/things/phase7Mqtt5Thing/shadow/update/accepted");
+
+ try (Mqtt5TestClient publisher = connectMqtt5("phase7-mqtt5-update-pub")) {
+ publisher.publish("$aws/things/phase7Mqtt5Thing/shadow/update",
+ json("{\"state\":{\"desired\":{\"color\":\"purple\"}},\"clientToken\":\"mqtt5-token\"}"));
+ }
+
+ MqttPublish accepted = subscriber.takePublish();
+ JsonNode payload = readJson(accepted.payload());
+ assertEquals("$aws/things/phase7Mqtt5Thing/shadow/update/accepted", accepted.topic());
+ assertEquals("purple", payload.path("state").path("desired").path("color").asText());
+ assertEquals("mqtt5-token", payload.path("clientToken").asText());
+ }
+ }
+
+
+ @Test
+ void malformedShadowUpdateTopicPublishesRejectedResponse() throws Exception {
+ try (MqttTestClient subscriber = connectMqtt("phase7-rejected-sub")) {
+ subscriber.subscribe("$aws/things/phase7Thing/shadow/update/rejected");
+
+ try (MqttTestClient publisher = connectMqtt("phase7-rejected-pub")) {
+ publisher.publish("$aws/things/phase7Thing/shadow/update", "{".getBytes(StandardCharsets.UTF_8));
+ }
+
+ MqttPublish rejected = subscriber.takePublish();
+ JsonNode payload = readJson(rejected.payload());
+ assertEquals("$aws/things/phase7Thing/shadow/update/rejected", rejected.topic());
+ assertEquals("InvalidRequestException", payload.path("code").asText());
+ assertTrue(payload.path("message").asText().length() > 0);
+ }
+ }
+
+ @Test
+ void shadowGetAndDeleteTopicsPublishAcceptedResponses() throws Exception {
+ try (MqttTestClient subscriber = connectMqtt("phase7-get-delete-sub")) {
+ subscriber.subscribe("$aws/things/phase7GetDelete/shadow/get/accepted");
+ subscriber.subscribe("$aws/things/phase7GetDelete/shadow/delete/accepted");
+
+ try (MqttTestClient publisher = connectMqtt("phase7-get-delete-pub")) {
+ publisher.publish("$aws/things/phase7GetDelete/shadow/update",
+ json("{\"state\":{\"reported\":{\"online\":true}}}"));
+ publisher.publish("$aws/things/phase7GetDelete/shadow/get", json("{\"clientToken\":\"get-token\"}"));
+ MqttPublish getAccepted = subscriber.takePublish();
+ JsonNode getPayload = readJson(getAccepted.payload());
+ assertEquals("$aws/things/phase7GetDelete/shadow/get/accepted", getAccepted.topic());
+ assertTrue(getPayload.path("state").path("reported").path("online").asBoolean());
+ assertEquals("get-token", getPayload.path("clientToken").asText());
+
+ publisher.publish("$aws/things/phase7GetDelete/shadow/delete", json("{\"clientToken\":\"delete-token\"}"));
+ MqttPublish deleteAccepted = subscriber.takePublish();
+ JsonNode deletePayload = readJson(deleteAccepted.payload());
+ assertEquals("$aws/things/phase7GetDelete/shadow/delete/accepted", deleteAccepted.topic());
+ assertTrue(deletePayload.path("state").path("reported").path("online").asBoolean());
+ assertEquals("delete-token", deletePayload.path("clientToken").asText());
+ }
+ }
+ }
+
+ @Test
+ void shadowUpdatePublishesDocumentsAndDeltaResponses() throws Exception {
+ try (MqttTestClient subscriber = connectMqtt("phase7-docs-delta-sub")) {
+ subscriber.subscribe("$aws/things/phase7Documents/shadow/update/documents");
+ subscriber.subscribe("$aws/things/phase7Documents/shadow/update/delta");
+
+ try (MqttTestClient publisher = connectMqtt("phase7-docs-delta-pub")) {
+ publisher.publish("$aws/things/phase7Documents/shadow/update",
+ json("{\"state\":{\"reported\":{\"color\":\"red\"}}}"));
+ subscriber.takePublish();
+
+ publisher.publish("$aws/things/phase7Documents/shadow/update",
+ json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"));
+ MqttPublish documents = subscriber.takePublish();
+ MqttPublish delta = subscriber.takePublish();
+ if (documents.topic().endsWith("/delta")) {
+ MqttPublish swap = documents;
+ documents = delta;
+ delta = swap;
+ }
+
+ JsonNode documentsPayload = readJson(documents.payload());
+ JsonNode deltaPayload = readJson(delta.payload());
+ assertEquals("$aws/things/phase7Documents/shadow/update/documents", documents.topic());
+ assertEquals("$aws/things/phase7Documents/shadow/update/delta", delta.topic());
+ assertEquals("red", documentsPayload.path("previous").path("state").path("reported").path("color").asText());
+ assertEquals("blue", documentsPayload.path("current").path("state").path("desired").path("color").asText());
+ assertEquals("blue", deltaPayload.path("state").path("color").asText());
+ }
+ }
+ }
+
+ @Test
+ void namedShadowTopicsPublishAcceptedResponses() throws Exception {
+ String thingName = "phase7NamedThing";
+ String updateTopic = "$aws/things/" + thingName + "/shadow/name/settings/update";
+ String getTopic = "$aws/things/" + thingName + "/shadow/name/settings/get";
+
+ try (MqttTestClient subscriber = connectMqtt("phase7-named-sub")) {
+ subscriber.subscribe(updateTopic + "/accepted");
+ subscriber.subscribe(getTopic + "/accepted");
+
+ try (MqttTestClient publisher = connectMqtt("phase7-named-pub")) {
+ publisher.publish(updateTopic,
+ json("{\"state\":{\"desired\":{\"mode\":\"auto\"}},\"clientToken\":\"named-update\"}"));
+ MqttPublish updateAccepted = subscriber.takePublish();
+ JsonNode updatePayload = readJson(updateAccepted.payload());
+ assertEquals(updateTopic + "/accepted", updateAccepted.topic());
+ assertEquals("auto", updatePayload.path("state").path("desired").path("mode").asText());
+ assertEquals("named-update", updatePayload.path("clientToken").asText());
+
+ publisher.publish(getTopic, json("{\"clientToken\":\"named-get\"}"));
+ MqttPublish getAccepted = subscriber.takePublish();
+ JsonNode getPayload = readJson(getAccepted.payload());
+ assertEquals(getTopic + "/accepted", getAccepted.topic());
+ assertEquals("auto", getPayload.path("state").path("desired").path("mode").asText());
+ assertEquals("named-get", getPayload.path("clientToken").asText());
+ }
+ }
+ }
+
+ @Test
+ void topicRuleRepublishPublishesToMqttSubscribers() throws Exception {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/phase8/mqtt/source'",
+ "actions": [
+ {
+ "republish": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "topic": "devices/phase8/mqtt/target"
+ }
+ }
+ ]
+ }
+ }
+ """)
+ .when()
+ .put("/rules/phase8MqttRepublishRule")
+ .then()
+ .statusCode(200);
+
+ try (MqttTestClient subscriber = connectMqtt("phase8-republish-sub")) {
+ subscriber.subscribe("devices/phase8/mqtt/target");
+
+ try (MqttTestClient publisher = connectMqtt("phase8-republish-pub")) {
+ publisher.publish("devices/phase8/mqtt/source", "mqtt-rule-payload".getBytes(StandardCharsets.UTF_8));
+ }
+
+ MqttPublish republished = subscriber.takePublish();
+ assertEquals("devices/phase8/mqtt/target", republished.topic());
+ assertArrayEquals("mqtt-rule-payload".getBytes(StandardCharsets.UTF_8), republished.payload());
+ }
+ }
+
+ private MqttTestClient connectMqtt(String clientId) throws MqttException {
+ return connectMqttClientId(uniqueClientId(clientId));
+ }
+
+ private MqttTestClient connectMqttClientId(String clientId) throws MqttException {
+ return MqttTestClient.connect(clientId);
+ }
+
+ private String uniqueClientId(String clientId) {
+ return clientId + "-" + System.nanoTime();
+ }
+
+ private Mqtt5TestClient connectMqtt5(String clientId) throws org.eclipse.paho.mqttv5.common.MqttException {
+ return Mqtt5TestClient.connect(uniqueClientId(clientId));
+ }
+
+ private byte[] json(String value) {
+ return value.getBytes(StandardCharsets.UTF_8);
+ }
+
+ private JsonNode readJson(byte[] payload) throws IOException {
+ return OBJECT_MAPPER.readTree(payload);
+ }
+
+ private void awaitPublishedEvent(String topic, byte[] payload) throws InterruptedException {
+ Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
+ while (Instant.now().isBefore(deadline)) {
+ boolean found = eventRecorder.recentEvents().stream()
+ .anyMatch(event -> topic.equals(event.topic()) && Arrays.equals(payload, event.payload()));
+ if (found) {
+ return;
+ }
+ Thread.sleep(25);
+ }
+ throw new AssertionError("MQTT publish event was not recorded");
+ }
+
+ private record MqttPublish(String topic, byte[] payload) {
+ }
+
+ private static final class MqttTestClient implements AutoCloseable {
+ private final MqttClient client;
+ private final BlockingQueue<MqttPublish> publishes = new LinkedBlockingQueue<>();
+
+ private MqttTestClient(MqttClient client) {
+ this.client = client;
+ }
+
+ static MqttTestClient connect(String clientId) throws MqttException {
+ MqttClient client = new MqttClient(BROKER_URI, clientId, new MemoryPersistence());
+ MqttTestClient testClient = new MqttTestClient(client);
+ client.setCallback(new MqttCallback() {
+ @Override
+ public void connectionLost(Throwable cause) {
+ }
+
+ @Override
+ public void messageArrived(String topic, MqttMessage message) {
+ testClient.publishes.add(new MqttPublish(topic, message.getPayload()));
+ }
+
+ @Override
+ public void deliveryComplete(IMqttDeliveryToken token) {
+ }
+ });
+ client.connect(connectOptions());
+ return testClient;
+ }
+
+ boolean isConnected() {
+ return client.isConnected();
+ }
+
+ void subscribe(String topic) throws MqttException {
+ subscribe(topic, 0);
+ }
+
+ void subscribe(String topic, int qos) throws MqttException {
+ client.subscribe(topic, qos);
+ }
+
+ void publish(String topic, byte[] payload) throws MqttException {
+ publish(topic, payload, 0);
+ }
+
+ void publish(String topic, byte[] payload, int qos) throws MqttException {
+ client.publish(topic, payload, qos, false);
+ }
+
+ MqttPublish takePublish() throws InterruptedException {
+ return Optional.ofNullable(publishes.poll(2, TimeUnit.SECONDS))
+ .orElseThrow(() -> new AssertionError("No MQTT publish received"));
+ }
+
+ void awaitDisconnected() throws InterruptedException {
+ Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
+ while (Instant.now().isBefore(deadline)) {
+ if (!client.isConnected()) {
+ return;
+ }
+ Thread.sleep(25);
+ }
+ throw new AssertionError("MQTT connection stayed open after DeleteConnection");
+ }
+
+ @Override
+ public void close() throws MqttException {
+ if (client.isConnected()) {
+ client.disconnect();
+ }
+ client.close();
+ }
+
+ private static MqttConnectOptions connectOptions() {
+ MqttConnectOptions options = new MqttConnectOptions();
+ options.setCleanSession(true);
+ options.setConnectionTimeout(2);
+ options.setKeepAliveInterval(60);
+ options.setAutomaticReconnect(false);
+ return options;
+ }
+ }
+
+ private static final class Mqtt5TestClient implements AutoCloseable {
+ private final org.eclipse.paho.mqttv5.client.MqttClient client;
+ private final BlockingQueue<MqttPublish> publishes = new LinkedBlockingQueue<>();
+
+ private Mqtt5TestClient(org.eclipse.paho.mqttv5.client.MqttClient client) {
+ this.client = client;
+ }
+
+ static Mqtt5TestClient connect(String clientId) throws org.eclipse.paho.mqttv5.common.MqttException {
+ org.eclipse.paho.mqttv5.client.MqttClient client =
+ new org.eclipse.paho.mqttv5.client.MqttClient(BROKER_URI, clientId, null);
+ Mqtt5TestClient testClient = new Mqtt5TestClient(client);
+ client.setCallback(new org.eclipse.paho.mqttv5.client.MqttCallback() {
+ @Override
+ public void disconnected(org.eclipse.paho.mqttv5.client.MqttDisconnectResponse disconnectResponse) {
+ }
+
+ @Override
+ public void mqttErrorOccurred(org.eclipse.paho.mqttv5.common.MqttException exception) {
+ }
+
+ @Override
+ public void messageArrived(String topic, org.eclipse.paho.mqttv5.common.MqttMessage message) {
+ testClient.publishes.add(new MqttPublish(topic, message.getPayload()));
+ }
+
+ @Override
+ public void deliveryComplete(org.eclipse.paho.mqttv5.client.IMqttToken token) {
+ }
+
+ @Override
+ public void connectComplete(boolean reconnect, String serverURI) {
+ }
+
+ @Override
+ public void authPacketArrived(int reasonCode, org.eclipse.paho.mqttv5.common.packet.MqttProperties properties) {
+ }
+ });
+ client.connect(connectOptions());
+ return testClient;
+ }
+
+ boolean isConnected() {
+ return client.isConnected();
+ }
+
+ void subscribe(String topic) throws org.eclipse.paho.mqttv5.common.MqttException {
+ client.subscribe(topic, 0);
+ }
+
+ void publish(String topic, byte[] payload) throws org.eclipse.paho.mqttv5.common.MqttException {
+ org.eclipse.paho.mqttv5.common.MqttMessage message = new org.eclipse.paho.mqttv5.common.MqttMessage(payload);
+ message.setQos(0);
+ client.publish(topic, message);
+ }
+
+ MqttPublish takePublish() throws InterruptedException {
+ return Optional.ofNullable(publishes.poll(2, TimeUnit.SECONDS))
+ .orElseThrow(() -> new AssertionError("No MQTT publish received"));
+ }
+
+ @Override
+ public void close() throws org.eclipse.paho.mqttv5.common.MqttException {
+ if (client.isConnected()) {
+ client.disconnect();
+ }
+ client.close();
+ }
+
+ private static org.eclipse.paho.mqttv5.client.MqttConnectionOptions connectOptions() {
+ org.eclipse.paho.mqttv5.client.MqttConnectionOptions options =
+ new org.eclipse.paho.mqttv5.client.MqttConnectionOptions();
+ options.setCleanStart(true);
+ options.setConnectionTimeout(2);
+ options.setKeepAliveInterval(60);
+ options.setAutomaticReconnect(false);
+ return options;
+ }
+ }
+
+ public static final class EnabledMqttProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of(
+ "floci.services.iot.mqtt.enabled", "true",
+ "floci.services.iot.mqtt.auto-start", "true",
+ "floci.services.iot.mqtt.host", "127.0.0.1",
+ "floci.services.iot.mqtt.port", Integer.toString(PORT)
+ );
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttLazyStartupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttLazyStartupIntegrationTest.java
new file mode 100644
index 0000000000..ad639300b4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttLazyStartupIntegrationTest.java
@@ -0,0 +1,87 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+@TestProfile(IotMqttLazyStartupIntegrationTest.LazyMqttProfile.class)
+class IotMqttLazyStartupIntegrationTest {
+
+ private static final int PORT = 18832;
+
+ @Inject
+ IotMqttBrokerService mqttBrokerService;
+
+ @BeforeEach
+ void stopBroker() {
+ mqttBrokerService.stop();
+ }
+
+ @Test
+ void enabledMqttDoesNotListenUntilEndpointDiscovery() throws Exception {
+ assertThrows(Exception.class, () -> {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", PORT), 250);
+ }
+ });
+
+ given()
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200);
+
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", PORT), 2_000);
+ assertTrue(socket.isConnected());
+ }
+ }
+
+ @Test
+ void createThingStartsMqttWhenEnabled() throws Exception {
+ assertThrows(Exception.class, () -> {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", PORT), 250);
+ }
+ });
+
+ given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/phase-six-lazy-create")
+ .then()
+ .statusCode(200)
+ .body("thingName", equalTo("phase-six-lazy-create"));
+
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", PORT), 2_000);
+ assertTrue(socket.isConnected());
+ }
+ }
+
+ public static final class LazyMqttProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of(
+ "floci.services.iot.mqtt.enabled", "true",
+ "floci.services.iot.mqtt.auto-start", "false",
+ "floci.services.iot.mqtt.host", "127.0.0.1",
+ "floci.services.iot.mqtt.port", Integer.toString(PORT)
+ );
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMvpAcceptanceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMvpAcceptanceIntegrationTest.java
new file mode 100644
index 0000000000..2ca53099f7
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMvpAcceptanceIntegrationTest.java
@@ -0,0 +1,156 @@
+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.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class IotMvpAcceptanceIntegrationTest {
+
+ @Test
+ void provisionCommunicateStoreStateAndRouteTelemetry() {
+ given()
+ .queryParam("endpointType", "iot:Data-ATS")
+ .when()
+ .get("/endpoint")
+ .then()
+ .statusCode(200)
+ .body("endpointAddress", notNullValue());
+
+ String thingName = "mvp-acceptance-thing";
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "attributePayload": {
+ "attributes": {
+ "env": "mvp"
+ }
+ }
+ }
+ """)
+ .when()
+ .post("/things/" + thingName)
+ .then()
+ .statusCode(200)
+ .body("thingName", equalTo(thingName));
+
+ String certificateArn = given()
+ .queryParam("setAsActive", true)
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .body("certificatePem", containsString("BEGIN CERTIFICATE"))
+ .extract()
+ .path("certificateArn");
+
+ String policyName = "mvp-acceptance-policy";
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "policyDocument": "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}"
+ }
+ """)
+ .when()
+ .post("/policies/" + policyName)
+ .then()
+ .statusCode(200)
+ .body("policyName", equalTo(policyName));
+
+ given()
+ .queryParam("target", certificateArn)
+ .when()
+ .put("/target-policies/" + policyName)
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("principal", certificateArn)
+ .when()
+ .put("/things/" + thingName + "/principals")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/things/" + thingName + "/principals")
+ .then()
+ .statusCode(200)
+ .body("principals", hasItem(certificateArn));
+
+ String queueUrl = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", "mvp-iot-rule-queue")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/mvp/telemetry'",
+ "ruleDisabled": false,
+ "actions": [
+ {
+ "sqs": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "queueUrl": "%s"
+ }
+ }
+ ]
+ }
+ }
+ """.formatted(queueUrl))
+ .when()
+ .put("/rules/mvpAcceptanceRule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("{\"state\":{\"desired\":{\"mode\":\"auto\"}}}")
+ .when()
+ .post("/things/" + thingName + "/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.mode", equalTo("auto"));
+
+ given()
+ .when()
+ .get("/things/" + thingName + "/shadow")
+ .then()
+ .statusCode(200)
+ .body("state.desired.mode", equalTo("auto"));
+
+ given()
+ .contentType("text/plain")
+ .body("mvp-telemetry")
+ .when()
+ .post("/topics/devices/mvp/telemetry")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MaxNumberOfMessages", "1")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("mvp-telemetry"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotThingOrganizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotThingOrganizationIntegrationTest.java
new file mode 100644
index 0000000000..ab0898d442
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotThingOrganizationIntegrationTest.java
@@ -0,0 +1,228 @@
+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.not;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class IotThingOrganizationIntegrationTest {
+
+ @Test
+ void thingTypesRoundTripAndTypedThingsDescribeTypeName() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingTypeProperties": {
+ "thingTypeDescription": "sensor devices",
+ "searchableAttributes": ["model"]
+ }
+ }
+ """)
+ .when()
+ .post("/thing-types/mvp2-sensor")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", equalTo("mvp2-sensor"))
+ .body("thingTypeArn", notNullValue())
+ .body("thingTypeId", notNullValue());
+
+ given()
+ .when()
+ .get("/thing-types/mvp2-sensor")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", equalTo("mvp2-sensor"))
+ .body("thingTypeProperties.thingTypeDescription", equalTo("sensor devices"))
+ .body("thingTypeProperties.searchableAttributes", hasItem("model"))
+ .body("thingTypeMetadata.deprecated", equalTo(false));
+
+ given()
+ .when()
+ .get("/thing-types")
+ .then()
+ .statusCode(200)
+ .body("thingTypes.thingTypeName", hasItem("mvp2-sensor"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingTypeProperties": {
+ "thingTypeDescription": "updated sensors",
+ "searchableAttributes": ["model", "firmware"]
+ }
+ }
+ """)
+ .when()
+ .patch("/thing-types/mvp2-sensor")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingTypeName": "mvp2-sensor",
+ "attributePayload": {"attributes": {"model": "a1"}}
+ }
+ """)
+ .when()
+ .post("/things/mvp2-typed-thing")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", equalTo("mvp2-sensor"));
+
+ given()
+ .when()
+ .get("/things/mvp2-typed-thing")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", equalTo("mvp2-sensor"));
+
+ given()
+ .when()
+ .post("/thing-types/mvp2-sensor/deprecate")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/thing-types/mvp2-sensor")
+ .then()
+ .statusCode(200)
+ .body("thingTypeMetadata.deprecated", equalTo(true));
+
+ given()
+ .when()
+ .delete("/things/mvp2-typed-thing")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .delete("/thing-types/mvp2-sensor")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ void thingGroupsRoundTripAndMembershipIsObservable() {
+ given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/things/mvp2-group-thing")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingGroupProperties": {
+ "thingGroupDescription": "mvp2 group",
+ "attributePayload": {"attributes": {"fleet": "alpha"}}
+ }
+ }
+ """)
+ .when()
+ .post("/thing-groups/mvp2-static-group")
+ .then()
+ .statusCode(200)
+ .body("thingGroupName", equalTo("mvp2-static-group"))
+ .body("thingGroupArn", notNullValue())
+ .body("thingGroupId", notNullValue());
+
+ given()
+ .when()
+ .get("/thing-groups/mvp2-static-group")
+ .then()
+ .statusCode(200)
+ .body("thingGroupName", equalTo("mvp2-static-group"))
+ .body("thingGroupProperties.thingGroupDescription", equalTo("mvp2 group"))
+ .body("thingGroupProperties.attributePayload.attributes.fleet", equalTo("alpha"));
+
+ given()
+ .when()
+ .get("/thing-groups")
+ .then()
+ .statusCode(200)
+ .body("thingGroups.groupName", hasItem("mvp2-static-group"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingGroupName": "mvp2-static-group",
+ "thingName": "mvp2-group-thing"
+ }
+ """)
+ .when()
+ .put("/thing-groups/addThingToThingGroup")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/thing-groups/mvp2-static-group/things")
+ .then()
+ .statusCode(200)
+ .body("things", hasItem("mvp2-group-thing"));
+
+ given()
+ .when()
+ .get("/things/mvp2-group-thing/thing-groups")
+ .then()
+ .statusCode(200)
+ .body("thingGroups.groupName", hasItem("mvp2-static-group"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingGroupProperties": {
+ "thingGroupDescription": "updated group",
+ "attributePayload": {"attributes": {"fleet": "beta"}}
+ },
+ "expectedVersion": 1
+ }
+ """)
+ .when()
+ .patch("/thing-groups/mvp2-static-group")
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(2));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "thingGroupName": "mvp2-static-group",
+ "thingName": "mvp2-group-thing"
+ }
+ """)
+ .when()
+ .put("/thing-groups/removeThingFromThingGroup")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/thing-groups/mvp2-static-group/things")
+ .then()
+ .statusCode(200)
+ .body("things", not(hasItem("mvp2-group-thing")));
+
+ given()
+ .when()
+ .delete("/thing-groups/mvp2-static-group")
+ .then()
+ .statusCode(200);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleIntegrationTest.java
new file mode 100644
index 0000000000..41b1d14039
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleIntegrationTest.java
@@ -0,0 +1,396 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Arrays;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class IotTopicRuleIntegrationTest {
+
+ @Inject
+ IotPublishEventRecorder eventRecorder;
+
+ @BeforeEach
+ void clearEvents() {
+ eventRecorder.clear();
+ }
+
+ @Test
+ void topicRuleMetadataRoundTrips() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/phase8/crud'",
+ "description": "phase 8 metadata",
+ "ruleDisabled": false,
+ "actions": [
+ {
+ "republish": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "topic": "devices/phase8/target"
+ }
+ }
+ ]
+ }
+ }
+ """)
+ .when()
+ .put("/rules/phase8CrudRule")
+ .then()
+ .statusCode(200)
+ .body("ruleArn", equalTo("arn:aws:iot:us-east-1:000000000000:rule/phase8CrudRule"))
+ .body("ruleName", equalTo("phase8CrudRule"));
+
+ given()
+ .when()
+ .get("/rules/phase8CrudRule")
+ .then()
+ .statusCode(200)
+ .body("ruleArn", equalTo("arn:aws:iot:us-east-1:000000000000:rule/phase8CrudRule"))
+ .body("rule.ruleName", equalTo("phase8CrudRule"))
+ .body("rule.sql", equalTo("SELECT * FROM 'devices/phase8/crud'"))
+ .body("rule.description", equalTo("phase 8 metadata"))
+ .body("rule.ruleDisabled", equalTo(false))
+ .body("rule.actions[0].republish.topic", equalTo("devices/phase8/target"))
+ .body("rule.createdAt", notNullValue());
+
+ given()
+ .when()
+ .post("/rules/phase8CrudRule/disable")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/rules")
+ .then()
+ .statusCode(200)
+ .body("rules.ruleName", hasItem("phase8CrudRule"))
+ .body("rules.find { it.ruleName == 'phase8CrudRule' }.ruleDisabled", equalTo(true));
+
+ given()
+ .when()
+ .post("/rules/phase8CrudRule/enable")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/rules/phase8CrudRule")
+ .then()
+ .statusCode(200)
+ .body("rule.ruleDisabled", equalTo(false));
+
+ given()
+ .when()
+ .delete("/rules/phase8CrudRule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/rules")
+ .then()
+ .statusCode(200)
+ .body("rules.ruleName", not(hasItem("phase8CrudRule")));
+ }
+
+ @Test
+ void matchingTopicRuleRepublishesOnlyMatchingPublishes() throws Exception {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/phase8/match/+'",
+ "actions": [
+ {
+ "republish": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "topic": "devices/phase8/republished"
+ }
+ }
+ ]
+ }
+ }
+ """)
+ .when()
+ .put("/rules/phase8RepublishRule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("text/plain")
+ .body("matched-payload")
+ .when()
+ .post("/topics/devices/phase8/match/one")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("text/plain")
+ .body("ignored-payload")
+ .when()
+ .post("/topics/devices/phase8/no-match")
+ .then()
+ .statusCode(200);
+
+ awaitPublishedEvent("devices/phase8/republished", "matched-payload".getBytes(StandardCharsets.UTF_8));
+ assertFalse(eventRecorder.recentEvents().stream()
+ .anyMatch(event -> "devices/phase8/republished".equals(event.topic())
+ && Arrays.equals("ignored-payload".getBytes(StandardCharsets.UTF_8), event.payload())));
+ }
+
+ @Test
+ void matchingTopicRuleSendsPayloadToSqs() {
+ String queueUrl = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", "phase8-iot-rule-queue")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/phase8/sqs'",
+ "actions": [
+ {
+ "sqs": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "queueUrl": "%s"
+ }
+ }
+ ]
+ }
+ }
+ """.formatted(queueUrl))
+ .when()
+ .put("/rules/phase8SqsRule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("text/plain")
+ .body("sqs-rule-payload")
+ .when()
+ .post("/topics/devices/phase8/sqs")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MaxNumberOfMessages", "1")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("sqs-rule-payload"));
+ }
+
+ @Test
+ void matchingTopicRulePublishesPayloadToSns() {
+ String queueUrl = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", "mvp1-iot-sns-rule-queue")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+
+ String topicArn = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateTopic")
+ .formParam("Name", "mvp1-iot-sns-rule-topic")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "Subscribe")
+ .formParam("TopicArn", topicArn)
+ .formParam("Protocol", "sqs")
+ .formParam("Endpoint", queueUrl)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/mvp1/sns'",
+ "actions": [
+ {
+ "sns": {
+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
+ "targetArn": "%s"
+ }
+ }
+ ]
+ }
+ }
+ """.formatted(topicArn))
+ .when()
+ .put("/rules/mvp1SnsRule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("text/plain")
+ .body("sns-rule-payload")
+ .when()
+ .post("/topics/devices/mvp1/sns")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MaxNumberOfMessages", "1")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("sns-rule-payload"));
+ }
+
+ @Test
+ void topicRuleConflictReplaceDeleteAndTagsMatchMvpLifecycle() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/mvp1/original'",
+ "description": "original",
+ "actions": []
+ }
+ }
+ """)
+ .when()
+ .put("/rules/mvp1Rule")
+ .then()
+ .statusCode(200)
+ .body("ruleArn", equalTo("arn:aws:iot:us-east-1:000000000000:rule/mvp1Rule"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/mvp1/original'",
+ "actions": []
+ }
+ }
+ """)
+ .when()
+ .put("/rules/mvp1Rule")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("ResourceAlreadyExistsException"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "resourceArn": "arn:aws:iot:us-east-1:000000000000:rule/mvp1Rule",
+ "tags": [{"Key": "env", "Value": "rule"}]
+ }
+ """)
+ .when()
+ .post("/tags")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("resourceArn", "arn:aws:iot:us-east-1:000000000000:rule/mvp1Rule")
+ .when()
+ .get("/tags")
+ .then()
+ .statusCode(200)
+ .body("tags.Key", hasItem("env"))
+ .body("tags.Value", hasItem("rule"));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "topicRulePayload": {
+ "sql": "SELECT * FROM 'devices/mvp1/replaced'",
+ "description": "replaced",
+ "actions": []
+ }
+ }
+ """)
+ .when()
+ .patch("/rules/mvp1Rule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/rules/mvp1Rule")
+ .then()
+ .statusCode(200)
+ .body("rule.sql", equalTo("SELECT * FROM 'devices/mvp1/replaced'"))
+ .body("rule.description", equalTo("replaced"));
+
+ given()
+ .when()
+ .delete("/rules/mvp1Rule")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .delete("/rules/mvp1Rule")
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ private void awaitPublishedEvent(String topic, byte[] payload) throws InterruptedException {
+ Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
+ while (Instant.now().isBefore(deadline)) {
+ boolean found = eventRecorder.recentEvents().stream()
+ .anyMatch(event -> topic.equals(event.topic()) && Arrays.equals(payload, event.payload()));
+ if (found) {
+ return;
+ }
+ Thread.sleep(25);
+ }
+ throw new AssertionError("IoT publish event was not recorded for topic " + topic);
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 51f66676e4..39af0794aa 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -244,3 +244,12 @@ floci:
enabled: true
s3vectors:
enabled: true
+ iot:
+ enabled: true
+ mqtt:
+ enabled: true
+ auto-start: false
+ host: 127.0.0.1
+ port: 1883
+ iotdata:
+ enabled: true