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

* feat: add IoT endpoint and thing registry

* feat: add IoT thing tagging

* feat: add IoT certificates and shadows

* feat: add IoT MQTT broker

* feat: upgrade IoT MQTT broker to Moquette 0.18

* feat: restore IoT reserved MQTT topics

* feat: add IoT topic rules engine

* feat: improve IoT thing registry compatibility

* feat: complete IoT MVP 1 compatibility

* feat: complete IoT MVP 2 compatibility

* feat: finish IoT MVP 2 coverage

* fix: disable IoT MQTT broker persistence

* fix(docker): include vendored Maven artifacts in source builds

* fix(iot): stabilize MQTT integration test sockets

* fix(iot): verify MQTT test connections

* fix(iot): use Paho for MQTT integration tests

* fix(iot): use Vert.x MQTT broker

---------

Co-authored-by: nathan <nathan@debian-dev-small.localdomain>
This commit is contained in:
nblomquistandnathan authored and GitHub committed 2026-06-25 22:58:44 -05:00
1 parent 54ba15c218
commit 326b495496
47 files changed
+8602 -19

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ mvnw.cmd text eol=crlf
*.fla binary
*.swf binary
*.gz binary
*.jar binary
*.zip binary
*.7z binary
*.ttf binary
+1
View File
@@ -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 \
+1
View File
@@ -2,6 +2,7 @@ target/
data/
*.class
*.jar
!vendor/maven/**/*.jar
*.war
.idea/
*.iml
+1
View File
@@ -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
@@ -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())
@@ -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
}
}
}
+13
View File
@@ -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>
@@ -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)
@@ -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) {
}
}
@@ -181,6 +181,24 @@ def sesv2_client(aws_config, client_config):
return boto3.client("sesv2", config=client_config, **aws_config)
@pytest.fixture
def iot_client(aws_config, client_config):
"""Create AWS IoT client."""
return boto3.client("iot", config=client_config, **aws_config)
@pytest.fixture
def iot_data_client(aws_config, client_config):
"""Create AWS IoT Data client."""
return boto3.client("iot-data", config=client_config, **aws_config)
@pytest.fixture
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
# ============================================
@@ -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)
+141
View File
@@ -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.
+1
View File
@@ -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
+21
View File
@@ -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>
@@ -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 {
@@ -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))
));
}
@@ -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() {
@@ -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);
File diff suppressed because it is too large. Load diff
@@ -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);
}
}
}
@@ -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) {
}
}
@@ -0,0 +1,4 @@
package io.github.hectorvent.floci.services.iot;
public record IotPublishEvent(String topic, byte[] payload) {
}
@@ -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();
}
}
File diff suppressed because it is too large. Load diff
@@ -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);
}
}
@@ -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); }
}
@@ -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; }
}
@@ -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; }
}
@@ -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; }
}
}
@@ -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; }
}
@@ -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; }
}
@@ -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; }
}
@@ -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; }
}
@@ -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);
}
}
@@ -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;
}
}
+9
View File
@@ -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
@@ -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));
}
}
@@ -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");
}
}
}
@@ -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");
}
}
@@ -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));
}
}
@@ -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)
);
}
}
}
@@ -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)
);
}
}
}
@@ -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)
);
}
}
}
@@ -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"));
}
}
@@ -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);
}
}
@@ -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);
}
}
+9
View File
@@ -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