diff --git a/README.md b/README.md index 278d4135f9..7ef69dd742 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ Floci supports local emulation for application services, data services, eventing | Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, KMS, Secrets Manager, SSM | | Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, CloudWatch Logs, CloudWatch Metrics | | API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Cloud Map | -| Containers and compute | ECS, EC2, EKS, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 | +| Containers and compute | ECS, EC2, Lightsail, EKS, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 | | Data, analytics, and AI | Athena, Glue, EMR, Firehose, OpenSearch, S3 Vectors, Textract, Transcribe, Bedrock Runtime | | Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache | | Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family | @@ -273,6 +273,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | Data Firehose | In-process | Streaming delivery, NDJSON flush to S3 | | ECS | Real Docker | Clusters, task definitions, tasks, services, capacity providers, task sets | | EC2 | Real Docker | RunInstances launches containers, SSH key injection, UserData, IMDS, VPC resources | +| Lightsail | In-process | Instances, disks, static IPs, key pairs, ports, tags, regions, blueprints, bundles, operations | | ACM | In-process | Certificate issuance and validation lifecycle | | ECR | In-process with real registry | Repositories, docker push / pull, image-backed Lambda functions | | Resource Groups Tagging API | In-process | GetResources, tag and untag resources, tag key and value discovery across services | diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 792bd23ddb..83cc331551 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -342,6 +342,11 @@ software.amazon.awssdk appsync + + + software.amazon.awssdk + lightsail + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index d109d3307c..6c9112e5bc 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -65,6 +65,7 @@ import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.backup.BackupClient; import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; import software.amazon.awssdk.services.appsync.AppSyncClient; +import software.amazon.awssdk.services.lightsail.LightsailClient; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.Change; import software.amazon.awssdk.services.route53.model.ChangeAction; @@ -835,6 +836,14 @@ public final class TestFixtures { .build(); } + public static LightsailClient lightsailClient() { + return LightsailClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static S3VectorsClient s3vectorsClient() { return S3VectorsClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LightsailTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LightsailTest.java new file mode 100644 index 0000000000..99e5d17e93 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LightsailTest.java @@ -0,0 +1,126 @@ +package com.floci.test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.lightsail.LightsailClient; +import software.amazon.awssdk.services.lightsail.model.CreateInstancesRequest; +import software.amazon.awssdk.services.lightsail.model.InstanceState; +import software.amazon.awssdk.services.lightsail.model.NetworkProtocol; +import software.amazon.awssdk.services.lightsail.model.PortInfo; +import software.amazon.awssdk.services.lightsail.model.Tag; + +import static org.assertj.core.api.Assertions.assertThat; + +class LightsailTest { + + private LightsailClient lightsail; + private String suffix; + + @BeforeEach + void setUp() { + lightsail = TestFixtures.lightsailClient(); + suffix = TestFixtures.uniqueName("ls"); + } + + @Test + void sdkCanCreateAndManageCoreLightsailResources() { + String instanceName = suffix + "-web"; + String diskName = suffix + "-data"; + String staticIpName = suffix + "-ip"; + String keyPairName = suffix + "-key"; + + assertThat(lightsail.getBlueprints().blueprints()) + .extracting("blueprintId") + .contains("ubuntu_22_04"); + assertThat(lightsail.getBundles().bundles()) + .extracting("bundleId") + .contains("nano_3_0"); + assertThat(lightsail.getRegions(r -> r.includeAvailabilityZones(true)).regions().get(0).availabilityZones()) + .isNotEmpty(); + + var keyPair = lightsail.createKeyPair(r -> r + .keyPairName(keyPairName) + .tags(Tag.builder().key("owner").value("sdk").build())); + assertThat(keyPair.keyPair().name()).isEqualTo(keyPairName); + assertThat(keyPair.keyPair().arn()).startsWith("arn:aws:lightsail:"); + assertThat(keyPair.privateKeyBase64()).isNotBlank(); + assertThat(keyPair.operation().operationTypeAsString()).isEqualTo("CreateKeyPair"); + + var createInstances = lightsail.createInstances(CreateInstancesRequest.builder() + .instanceNames(instanceName) + .availabilityZone("us-east-1a") + .blueprintId("ubuntu_22_04") + .bundleId("nano_3_0") + .keyPairName(keyPairName) + .tags(Tag.builder().key("component").value("web").build()) + .build()); + assertThat(createInstances.operations()).hasSize(1); + assertThat(createInstances.operations().get(0).operationTypeAsString()).isEqualTo("CreateInstance"); + + var instance = lightsail.getInstance(r -> r.instanceName(instanceName)).instance(); + assertThat(instance.name()).isEqualTo(instanceName); + assertThat(instance.arn()).startsWith("arn:aws:lightsail:"); + assertThat(instance.location().regionNameAsString()).isEqualTo("us-east-1"); + assertThat(instance.location().availabilityZone()).isEqualTo("us-east-1a"); + assertThat(instance.state().name()).isEqualTo("running"); + assertThat(instance.tags()).extracting(Tag::key).contains("component"); + + lightsail.stopInstance(r -> r.instanceName(instanceName)); + InstanceState stopped = lightsail.getInstanceState(r -> r.instanceName(instanceName)).state(); + assertThat(stopped.name()).isEqualTo("stopped"); + assertThat(stopped.code()).isEqualTo(80); + lightsail.startInstance(r -> r.instanceName(instanceName)); + assertThat(lightsail.getInstance(r -> r.instanceName(instanceName)).instance().state().name()).isEqualTo("running"); + + lightsail.openInstancePublicPorts(r -> r + .instanceName(instanceName) + .portInfo(PortInfo.builder() + .fromPort(80) + .toPort(80) + .protocol(NetworkProtocol.TCP) + .cidrs("0.0.0.0/0") + .build())); + assertThat(lightsail.getInstancePortStates(r -> r.instanceName(instanceName)).portStates()) + .anySatisfy(port -> { + assertThat(port.fromPort()).isEqualTo(80); + assertThat(port.toPort()).isEqualTo(80); + assertThat(port.protocol()).isEqualTo(NetworkProtocol.TCP); + assertThat(port.stateAsString()).isEqualTo("open"); + }); + + lightsail.createDisk(r -> r.diskName(diskName).availabilityZone("us-east-1a").sizeInGb(8)); + lightsail.attachDisk(r -> r.diskName(diskName).instanceName(instanceName).diskPath("/dev/xvdf")); + var disk = lightsail.getDisk(r -> r.diskName(diskName)).disk(); + assertThat(disk.name()).isEqualTo(diskName); + assertThat(disk.attachedTo()).isEqualTo(instanceName); + assertThat(disk.isAttached()).isTrue(); + + lightsail.allocateStaticIp(r -> r.staticIpName(staticIpName)); + lightsail.attachStaticIp(r -> r.staticIpName(staticIpName).instanceName(instanceName)); + var staticIp = lightsail.getStaticIp(r -> r.staticIpName(staticIpName)).staticIp(); + assertThat(staticIp.name()).isEqualTo(staticIpName); + assertThat(staticIp.attachedTo()).isEqualTo(instanceName); + assertThat(staticIp.isAttached()).isTrue(); + + lightsail.tagResource(r -> r.resourceName(instanceName) + .tags(Tag.builder().key("env").value("test").build())); + assertThat(lightsail.getInstance(r -> r.instanceName(instanceName)).instance().tags()) + .extracting(Tag::key) + .contains("component", "env"); + + assertThat(lightsail.getActiveNames().activeNames()) + .contains(instanceName, diskName, staticIpName, keyPairName); + assertThat(lightsail.getOperationsForResource(r -> r.resourceName(instanceName)).operations()) + .isNotEmpty(); + assertThat(lightsail.getBuckets(r -> {}).buckets()).isEmpty(); + + lightsail.detachStaticIp(r -> r.staticIpName(staticIpName)); + lightsail.releaseStaticIp(r -> r.staticIpName(staticIpName)); + lightsail.detachDisk(r -> r.diskName(diskName)); + lightsail.deleteDisk(r -> r.diskName(diskName)); + lightsail.deleteInstance(r -> r.instanceName(instanceName)); + lightsail.deleteKeyPair(r -> r.keyPairName(keyPairName)); + + assertThat(lightsail.getInstances().instances()).noneMatch(i -> instanceName.equals(i.name())); + } +} diff --git a/docs/index.md b/docs/index.md index 677e393af4..e9e635e3fc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -46,6 +46,7 @@ Floci emulates 68 AWS services. See the [Services Overview](services/index.md) f | Data Firehose | JSON 1.1 | | ECS | JSON 1.1 | | EC2 | EC2 Query | +| Lightsail | JSON 1.1 | | ACM | JSON 1.1 | | ECR | JSON 1.1 + OCI Distribution | | Resource Groups Tagging API | JSON 1.1 | diff --git a/docs/services/index.md b/docs/services/index.md index f99b19fcc8..b71a744f0d 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -47,6 +47,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 6 | | [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 58 | | [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 78 | +| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 12 | | [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane via `registry:2`) | JSON 1.1 + OCI Distribution | 17 | | [Resource Groups Tagging API](resource-groups-tagging.md) | `POST /` + `X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*` | JSON 1.1 | 5 | diff --git a/docs/services/lightsail.md b/docs/services/lightsail.md new file mode 100644 index 0000000000..70b305f924 --- /dev/null +++ b/docs/services/lightsail.md @@ -0,0 +1,58 @@ +# Amazon Lightsail + +Floci exposes Amazon Lightsail through the AWS JSON 1.1 protocol: + +- Endpoint: `POST /` +- Target prefix: `Lightsail_20161128.*` +- Signing name: `lightsail` + +The local implementation keeps Lightsail state in Floci storage and is designed for SDK and AWS CLI compatibility on common development workflows. + +## Supported local workflows + +- Instances: create, get, list, start, stop, reboot, delete, state lookup, and public port management +- Disks: create, get, list, attach, detach, and delete +- Static IPs: allocate, get, list, attach, detach, and release +- Key pairs: create, import, get, list, delete, and download default key pair +- Discovery: regions, blueprints, bundles, active names, operations, and operations for resource +- Tags: tag and untag local Lightsail resources + +Read-only list operations for cloud-side Lightsail resource families that are not locally implemented yet return empty AWS-shaped lists. Cloud-only provisioning workflows such as container services, distributions, managed databases, load balancers, buckets, and snapshots are recognized from the AWS Lightsail API model and return an explicit `UnsupportedOperation` error instead of a custom endpoint or non-AWS response shape. + +## Examples + +```bash +aws --endpoint-url http://localhost:4566 lightsail get-blueprints +``` + +```bash +aws --endpoint-url http://localhost:4566 lightsail create-instances \ + --instance-names web-a \ + --availability-zone us-east-1a \ + --blueprint-id ubuntu_22_04 \ + --bundle-id nano_3_0 +``` + +```bash +aws --endpoint-url http://localhost:4566 lightsail allocate-static-ip \ + --static-ip-name web-ip + +aws --endpoint-url http://localhost:4566 lightsail attach-static-ip \ + --static-ip-name web-ip \ + --instance-name web-a +``` + +## Persistence + +Lightsail resources use `StorageFactory` and follow the global storage mode by default. Configure the service with: + +```yaml +floci: + services: + lightsail: + enabled: true + storage: + services: + lightsail: + flush-interval-ms: 5000 +``` diff --git a/mkdocs.yml b/mkdocs.yml index 920885db5e..5f9e27ddc6 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -111,6 +111,7 @@ nav: - EKS: services/eks.md - OpenSearch: services/opensearch.md - EC2: services/ec2.md + - Lightsail: services/lightsail.md - AppConfig: services/appconfig.md - Bedrock Runtime: services/bedrock-runtime.md - ELB v2: services/elb.md diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 6c0678f8c3..f131ba9615 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -256,6 +256,7 @@ public interface EmulatorConfig { CloudFrontStorageConfig cloudfront(); AppSyncStorageConfig appsync(); BatchStorageConfig batch(); + LightsailStorageConfig lightsail(); CodePipelineStorageConfig codepipeline(); S3VectorsStorageConfig s3vectors(); EcsStorageConfig ecs(); @@ -403,6 +404,13 @@ public interface EmulatorConfig { long flushIntervalMs(); } + interface LightsailStorageConfig { + Optional mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface CodePipelineStorageConfig { Optional mode(); @@ -551,6 +559,7 @@ public interface EmulatorConfig { CloudFrontServiceConfig cloudfront(); AppSyncServiceConfig appsync(); BatchServiceConfig batch(); + LightsailServiceConfig lightsail(); UiServiceConfig ui(); S3VectorsServiceConfig s3vectors(); IotServiceConfig iot(); @@ -588,6 +597,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface LightsailServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface CloudControlServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 4095e2ad5c..d191bb0139 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.transfer.TransferHandler; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.firehose.FirehoseJsonHandler; import io.github.hectorvent.floci.services.glue.GlueJsonHandler; +import io.github.hectorvent.floci.services.lightsail.LightsailJsonHandler; import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler; import io.github.hectorvent.floci.services.bcmdataexports.BcmDataExportsJsonHandler; import io.github.hectorvent.floci.services.ce.CostExplorerJsonHandler; @@ -92,6 +93,7 @@ public class AwsJson11Controller { private final BcmDataExportsJsonHandler bcmDataExportsJsonHandler; private final ConfigServiceJsonHandler configServiceJsonHandler; private final CloudTrailJsonHandler cloudTrailJsonHandler; + private final LightsailJsonHandler lightsailJsonHandler; private final CloudControlJsonHandler cloudControlJsonHandler; @Inject @@ -125,6 +127,7 @@ public class AwsJson11Controller { BcmDataExportsJsonHandler bcmDataExportsJsonHandler, ConfigServiceJsonHandler configServiceJsonHandler, CloudTrailJsonHandler cloudTrailJsonHandler, + LightsailJsonHandler lightsailJsonHandler, CloudControlJsonHandler cloudControlJsonHandler) { this.objectMapper = objectMapper; this.catalog = catalog; @@ -161,6 +164,7 @@ public class AwsJson11Controller { this.bcmDataExportsJsonHandler = bcmDataExportsJsonHandler; this.configServiceJsonHandler = configServiceJsonHandler; this.cloudTrailJsonHandler = cloudTrailJsonHandler; + this.lightsailJsonHandler = lightsailJsonHandler; this.cloudControlJsonHandler = cloudControlJsonHandler; } @@ -223,6 +227,7 @@ public class AwsJson11Controller { case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region); case "config" -> configServiceJsonHandler.handle(action, request, region); case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region); + case "lightsail" -> lightsailJsonHandler.handle(action, request, region); case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region); default -> null; }; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index fc29b43052..7a8b7c00d7 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -289,6 +289,11 @@ public class ResolvedServiceCatalog { protocols(ServiceProtocol.JSON), Set.of("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101."), Set.of("cloudtrail"), Set.of(), Set.of()), + descriptor("lightsail", "lightsail", config.services().lightsail().enabled(), true, + "lightsail", storageMode(config.storage().services().lightsail().mode(), config.storage().mode()), + config.storage().services().lightsail().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("Lightsail_20161128."), Set.of("lightsail"), Set.of(), Set.of()), descriptor("cloudcontrol", "cloudcontrol", config.services().cloudcontrol().enabled(), true, null, null, 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailJsonHandler.java new file mode 100644 index 0000000000..0266aff7be --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailJsonHandler.java @@ -0,0 +1,181 @@ +package io.github.hectorvent.floci.services.lightsail; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.Map; +import java.util.Set; + +@ApplicationScoped +public class LightsailJsonHandler { + + private static final Set ACTIONS = Set.of( + "AllocateStaticIp", "AttachCertificateToDistribution", "AttachDisk", "AttachInstancesToLoadBalancer", + "AttachLoadBalancerTlsCertificate", "AttachStaticIp", "CloseInstancePublicPorts", "CopySnapshot", + "CreateBucket", "CreateBucketAccessKey", "CreateCertificate", "CreateCloudFormationStack", + "CreateContactMethod", "CreateContainerService", "CreateContainerServiceDeployment", + "CreateContainerServiceRegistryLogin", "CreateDisk", "CreateDiskFromSnapshot", "CreateDiskSnapshot", + "CreateDistribution", "CreateDomain", "CreateDomainEntry", "CreateGUISessionAccessDetails", + "CreateInstanceSnapshot", "CreateInstances", "CreateInstancesFromSnapshot", "CreateKeyPair", + "CreateLoadBalancer", "CreateLoadBalancerTlsCertificate", "CreateRelationalDatabase", + "CreateRelationalDatabaseFromSnapshot", "CreateRelationalDatabaseSnapshot", "DeleteAlarm", + "DeleteAutoSnapshot", "DeleteBucket", "DeleteBucketAccessKey", "DeleteCertificate", + "DeleteContactMethod", "DeleteContainerImage", "DeleteContainerService", "DeleteDisk", + "DeleteDiskSnapshot", "DeleteDistribution", "DeleteDomain", "DeleteDomainEntry", "DeleteInstance", + "DeleteInstanceSnapshot", "DeleteKeyPair", "DeleteKnownHostKeys", "DeleteLoadBalancer", + "DeleteLoadBalancerTlsCertificate", "DeleteRelationalDatabase", "DeleteRelationalDatabaseSnapshot", + "DetachCertificateFromDistribution", "DetachDisk", "DetachInstancesFromLoadBalancer", "DetachStaticIp", + "DisableAddOn", "DownloadDefaultKeyPair", "EnableAddOn", "ExportSnapshot", "GetActiveNames", + "GetAlarms", "GetAutoSnapshots", "GetBlueprints", "GetBucketAccessKeys", "GetBucketBundles", + "GetBucketMetricData", "GetBuckets", "GetBundles", "GetCertificates", "GetCloudFormationStackRecords", + "GetContactMethods", "GetContainerAPIMetadata", "GetContainerImages", "GetContainerLog", + "GetContainerServiceDeployments", "GetContainerServiceMetricData", "GetContainerServicePowers", + "GetContainerServices", "GetCostEstimate", "GetDisk", "GetDiskSnapshot", "GetDiskSnapshots", + "GetDisks", "GetDistributionBundles", "GetDistributionLatestCacheReset", "GetDistributionMetricData", + "GetDistributions", "GetDomain", "GetDomains", "GetExportSnapshotRecords", "GetInstance", + "GetInstanceAccessDetails", "GetInstanceMetricData", "GetInstancePortStates", "GetInstanceSnapshot", + "GetInstanceSnapshots", "GetInstanceState", "GetInstances", "GetKeyPair", "GetKeyPairs", + "GetLoadBalancer", "GetLoadBalancerMetricData", "GetLoadBalancerTlsCertificates", + "GetLoadBalancerTlsPolicies", "GetLoadBalancers", "GetOperation", "GetOperations", + "GetOperationsForResource", "GetRegions", "GetRelationalDatabase", "GetRelationalDatabaseBlueprints", + "GetRelationalDatabaseBundles", "GetRelationalDatabaseEvents", "GetRelationalDatabaseLogEvents", + "GetRelationalDatabaseLogStreams", "GetRelationalDatabaseMasterUserPassword", + "GetRelationalDatabaseMetricData", "GetRelationalDatabaseParameters", "GetRelationalDatabaseSnapshot", + "GetRelationalDatabaseSnapshots", "GetRelationalDatabases", "GetSetupHistory", "GetStaticIp", + "GetStaticIps", "ImportKeyPair", "IsVpcPeered", "OpenInstancePublicPorts", "PeerVpc", "PutAlarm", + "PutInstancePublicPorts", "RebootInstance", "RebootRelationalDatabase", "RegisterContainerImage", + "ReleaseStaticIp", "ResetDistributionCache", "SendContactMethodVerification", "SetIpAddressType", + "SetResourceAccessForBucket", "SetupInstanceHttps", "StartGUISession", "StartInstance", + "StartRelationalDatabase", "StopGUISession", "StopInstance", "StopRelationalDatabase", "TagResource", + "TestAlarm", "UnpeerVpc", "UntagResource", "UpdateBucket", "UpdateBucketBundle", + "UpdateContainerService", "UpdateDistribution", "UpdateDistributionBundle", "UpdateDomainEntry", + "UpdateInstanceMetadataOptions", "UpdateLoadBalancerAttribute", "UpdateRelationalDatabase", + "UpdateRelationalDatabaseParameters" + ); + + private static final Map EMPTY_LIST_RESULTS = Map.ofEntries( + Map.entry("GetAlarms", "alarms"), + Map.entry("GetAutoSnapshots", "autoSnapshots"), + Map.entry("GetBucketAccessKeys", "accessKeys"), + Map.entry("GetBucketBundles", "bundles"), + Map.entry("GetBucketMetricData", "metricData"), + Map.entry("GetBuckets", "buckets"), + Map.entry("GetCertificates", "certificates"), + Map.entry("GetCloudFormationStackRecords", "cloudFormationStackRecords"), + Map.entry("GetContactMethods", "contactMethods"), + Map.entry("GetContainerAPIMetadata", "metadata"), + Map.entry("GetContainerImages", "containerImages"), + Map.entry("GetContainerLog", "logEvents"), + Map.entry("GetContainerServiceDeployments", "deployments"), + Map.entry("GetContainerServiceMetricData", "metricData"), + Map.entry("GetContainerServicePowers", "powers"), + Map.entry("GetContainerServices", "containerServices"), + Map.entry("GetCostEstimate", "resourcesBudgetEstimate"), + Map.entry("GetDiskSnapshots", "diskSnapshots"), + Map.entry("GetDistributionBundles", "bundles"), + Map.entry("GetDistributionMetricData", "metricData"), + Map.entry("GetDistributions", "distributions"), + Map.entry("GetDomains", "domains"), + Map.entry("GetExportSnapshotRecords", "exportSnapshotRecords"), + Map.entry("GetInstanceMetricData", "metricData"), + Map.entry("GetInstanceSnapshots", "instanceSnapshots"), + Map.entry("GetLoadBalancerMetricData", "metricData"), + Map.entry("GetLoadBalancerTlsCertificates", "tlsCertificates"), + Map.entry("GetLoadBalancerTlsPolicies", "tlsPolicies"), + Map.entry("GetLoadBalancers", "loadBalancers"), + Map.entry("GetRelationalDatabaseBlueprints", "blueprints"), + Map.entry("GetRelationalDatabaseBundles", "bundles"), + Map.entry("GetRelationalDatabaseEvents", "relationalDatabaseEvents"), + Map.entry("GetRelationalDatabaseLogEvents", "resourceLogEvents"), + Map.entry("GetRelationalDatabaseLogStreams", "logStreams"), + Map.entry("GetRelationalDatabaseMetricData", "metricData"), + Map.entry("GetRelationalDatabaseParameters", "parameters"), + Map.entry("GetRelationalDatabaseSnapshots", "relationalDatabaseSnapshots"), + Map.entry("GetRelationalDatabases", "relationalDatabases"), + Map.entry("GetSetupHistory", "setupHistory") + ); + + private final LightsailService service; + + @Inject + public LightsailJsonHandler(LightsailService service) { + this.service = service; + } + + public Response handle(String action, JsonNode request, String region) { + return switch (action) { + case "CreateInstances" -> ok(service.createInstances(region, request)); + case "GetInstances" -> ok(service.getInstances(region)); + case "GetInstance" -> ok(service.getInstance(region, required(request, "instanceName"))); + case "DeleteInstance" -> ok(service.deleteInstance(region, required(request, "instanceName"))); + case "StartInstance" -> ok(service.startInstance(region, required(request, "instanceName"))); + case "StopInstance" -> ok(service.stopInstance(region, required(request, "instanceName"))); + case "RebootInstance" -> ok(service.rebootInstance(region, required(request, "instanceName"))); + case "GetInstanceState" -> ok(service.getInstanceState(region, required(request, "instanceName"))); + case "GetInstancePortStates" -> ok(service.getInstancePortStates(region, required(request, "instanceName"))); + case "OpenInstancePublicPorts" -> ok(service.putInstancePorts(region, requiredInstanceName(request), request, true)); + case "PutInstancePublicPorts" -> ok(service.putInstancePorts(region, requiredInstanceName(request), request, false)); + case "CloseInstancePublicPorts" -> ok(service.closeInstancePorts(region, requiredInstanceName(request), request)); + case "CreateDisk" -> ok(service.createDisk(region, request)); + case "GetDisks" -> ok(service.getDisks(region)); + case "GetDisk" -> ok(service.getDisk(region, required(request, "diskName"))); + case "AttachDisk" -> ok(service.attachDisk(region, request)); + case "DetachDisk" -> ok(service.detachDisk(region, required(request, "diskName"))); + case "DeleteDisk" -> ok(service.deleteDisk(region, required(request, "diskName"))); + case "AllocateStaticIp" -> ok(service.allocateStaticIp(region, required(request, "staticIpName"))); + case "GetStaticIps" -> ok(service.getStaticIps(region)); + case "GetStaticIp" -> ok(service.getStaticIp(region, required(request, "staticIpName"))); + case "AttachStaticIp" -> ok(service.attachStaticIp(region, request)); + case "DetachStaticIp" -> ok(service.detachStaticIp(region, required(request, "staticIpName"))); + case "ReleaseStaticIp" -> ok(service.releaseStaticIp(region, required(request, "staticIpName"))); + case "CreateKeyPair" -> ok(service.createKeyPair(region, request)); + case "ImportKeyPair" -> ok(service.importKeyPair(region, request)); + case "DownloadDefaultKeyPair" -> ok(service.downloadDefaultKeyPair(region)); + case "GetKeyPairs" -> ok(service.getKeyPairs(region)); + case "GetKeyPair" -> ok(service.getKeyPair(region, required(request, "keyPairName"))); + case "DeleteKeyPair" -> ok(service.deleteKeyPair(region, required(request, "keyPairName"))); + case "GetRegions" -> ok(service.getRegions(request)); + case "GetBlueprints" -> ok(service.getBlueprints()); + case "GetBundles" -> ok(service.getBundles()); + case "TagResource" -> ok(service.tagResource(region, request)); + case "UntagResource" -> ok(service.untagResource(region, request)); + case "GetActiveNames" -> ok(service.getActiveNames(region)); + case "GetOperations" -> ok(service.getOperations(region)); + case "GetOperationsForResource" -> ok(service.getOperationsForResource(region, required(request, "resourceName"))); + case "GetOperation" -> ok(service.getOperation(region, required(request, "operationId"))); + case "IsVpcPeered" -> ok(service.isVpcPeered()); + default -> handleDefault(action); + }; + } + + private Response handleDefault(String action) { + String fieldName = EMPTY_LIST_RESULTS.get(action); + if (fieldName != null) { + return ok(service.emptyList(fieldName)); + } + if (ACTIONS.contains(action)) { + throw new AwsException("UnsupportedOperation", + "Operation " + action + " is recognized by Amazon Lightsail but is not implemented in Floci.", 400); + } + throw new AwsException("UnknownOperationException", "Unknown operation " + action, 404); + } + + private static Response ok(JsonNode response) { + return Response.ok(response).build(); + } + + private static String requiredInstanceName(JsonNode request) { + return required(request, "instanceName"); + } + + private static String required(JsonNode request, String field) { + String value = request.path(field).asText(null); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidInputException", field + " is required", 400); + } + return value; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java new file mode 100644 index 0000000000..235a052655 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java @@ -0,0 +1,859 @@ +package io.github.hectorvent.floci.services.lightsail; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@ApplicationScoped +public class LightsailService { + + private static final String SERVICE = "lightsail"; + private static final String RESOURCE_INSTANCE = "Instance"; + private static final String RESOURCE_DISK = "Disk"; + private static final String RESOURCE_STATIC_IP = "StaticIp"; + private static final String RESOURCE_KEY_PAIR = "KeyPair"; + + private final StorageBackend resourceStore; + private final StorageBackend operationStore; + private final ObjectMapper mapper; + private final RegionResolver regionResolver; + + @Inject + public LightsailService(StorageFactory storageFactory, ObjectMapper mapper, RegionResolver regionResolver) { + this.resourceStore = storageFactory.create(SERVICE, "lightsail-resources.json", + new TypeReference>() {}); + this.operationStore = storageFactory.create(SERVICE, "lightsail-operations.json", + new TypeReference>() {}); + this.mapper = mapper; + this.regionResolver = regionResolver; + } + + public ObjectNode createInstances(String region, JsonNode request) { + requireArray(request, "instanceNames"); + requireText(request, "availabilityZone"); + String blueprintId = requireText(request, "blueprintId"); + String bundleId = requireText(request, "bundleId"); + String availabilityZone = request.path("availabilityZone").asText(); + ArrayNode operations = mapper.createArrayNode(); + + for (JsonNode nameNode : request.path("instanceNames")) { + String name = nameNode.asText(null); + requireName(name, "instanceNames"); + ensureNotExists(region, RESOURCE_INSTANCE, name); + + ObjectNode instance = baseResource(region, availabilityZone, RESOURCE_INSTANCE, name); + instance.put("blueprintId", blueprintId); + instance.put("blueprintName", blueprintName(blueprintId)); + instance.put("bundleId", bundleId); + instance.set("addOns", mapper.createArrayNode()); + instance.put("isStaticIp", false); + instance.put("privateIpAddress", privateIpFor(name)); + instance.put("publicIpAddress", publicIpFor(name)); + instance.set("ipv6Addresses", mapper.createArrayNode()); + instance.put("ipAddressType", request.path("ipAddressType").asText("ipv4")); + instance.set("hardware", hardware(bundleId)); + instance.set("networking", defaultNetworking()); + instance.set("state", instanceState("running")); + instance.put("username", defaultUsername(blueprintId)); + if (request.hasNonNull("keyPairName")) { + instance.put("sshKeyName", request.path("keyPairName").asText()); + } + instance.set("tags", tags(request.path("tags"))); + instance.set("metadataOptions", mapper.createObjectNode() + .put("state", "applied") + .put("httpTokens", "optional") + .put("httpEndpoint", "enabled") + .put("httpPutResponseHopLimit", 1)); + + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + operations.add(operation(region, RESOURCE_INSTANCE, name, "CreateInstance")); + } + + return mapper.createObjectNode().set("operations", operations); + } + + public ObjectNode getInstances(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode instances = response.putArray("instances"); + listResources(region, RESOURCE_INSTANCE).forEach(instances::add); + return response; + } + + public ObjectNode getInstance(String region, String name) { + return mapper.createObjectNode().set("instance", requireResource(region, RESOURCE_INSTANCE, name)); + } + + public ObjectNode deleteInstance(String region, String name) { + requireResource(region, RESOURCE_INSTANCE, name); + resourceStore.delete(resourceKey(region, RESOURCE_INSTANCE, name)); + detachStaticIpsFrom(name); + detachDisksFrom(name); + return operations(region, RESOURCE_INSTANCE, name, "DeleteInstance"); + } + + public ObjectNode startInstance(String region, String name) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + instance.set("state", instanceState("running")); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + return operations(region, RESOURCE_INSTANCE, name, "StartInstance"); + } + + public ObjectNode stopInstance(String region, String name) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + instance.set("state", instanceState("stopped")); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + return operations(region, RESOURCE_INSTANCE, name, "StopInstance"); + } + + public ObjectNode rebootInstance(String region, String name) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + instance.set("state", instanceState("running")); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + return operations(region, RESOURCE_INSTANCE, name, "RebootInstance"); + } + + public ObjectNode getInstanceState(String region, String name) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + return mapper.createObjectNode().set("state", instance.path("state").deepCopy()); + } + + public ObjectNode getInstancePortStates(String region, String name) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + ObjectNode response = mapper.createObjectNode(); + ArrayNode states = response.putArray("portStates"); + for (JsonNode port : instance.path("networking").path("ports")) { + ObjectNode state = port.deepCopy(); + state.put("state", "open"); + states.add(state); + } + return response; + } + + public ObjectNode putInstancePorts(String region, String name, JsonNode request, boolean merge) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + ArrayNode ports = mapper.createArrayNode(); + if (merge) { + instance.path("networking").path("ports").forEach(port -> ports.add(port.deepCopy())); + } + JsonNode portInfos = request.path("portInfos"); + if (portInfos.isMissingNode() && request.has("portInfo")) { + portInfos = mapper.createArrayNode().add(request.path("portInfo")); + } + if (portInfos.isMissingNode() || !portInfos.isArray()) { + throw new AwsException("InvalidInputException", "portInfo or portInfos is required", 400); + } + for (JsonNode portInfo : portInfos) { + ports.add(portInfo.deepCopy()); + } + ((ObjectNode) instance.path("networking")).set("ports", ports); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + return mapper.createObjectNode().set("operation", operation(region, RESOURCE_INSTANCE, name, + merge ? "OpenInstancePublicPorts" : "PutInstancePublicPorts")); + } + + public ObjectNode closeInstancePorts(String region, String name, JsonNode request) { + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, name); + JsonNode target = request.path("portInfo"); + if (target.isMissingNode()) { + throw new AwsException("InvalidInputException", "portInfo is required", 400); + } + ArrayNode remaining = mapper.createArrayNode(); + for (JsonNode port : instance.path("networking").path("ports")) { + if (!samePort(port, target)) { + remaining.add(port.deepCopy()); + } + } + ((ObjectNode) instance.path("networking")).set("ports", remaining); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, name), instance); + return mapper.createObjectNode().set("operation", operation(region, RESOURCE_INSTANCE, name, + "CloseInstancePublicPorts")); + } + + public ObjectNode createDisk(String region, JsonNode request) { + String name = requireText(request, "diskName"); + String availabilityZone = requireText(request, "availabilityZone"); + ensureNotExists(region, RESOURCE_DISK, name); + + ObjectNode disk = baseResource(region, availabilityZone, RESOURCE_DISK, name); + disk.set("addOns", mapper.createArrayNode()); + disk.put("sizeInGb", request.path("sizeInGb").asInt(8)); + disk.put("isSystemDisk", false); + disk.put("iops", Math.max(100, request.path("sizeInGb").asInt(8) * 3)); + disk.put("path", "/dev/xvdf"); + disk.put("state", "available"); + disk.put("isAttached", false); + disk.put("attachmentState", "detached"); + disk.put("gbInUse", 0); + disk.put("autoMountStatus", "NotMounted"); + disk.set("tags", tags(request.path("tags"))); + resourceStore.put(resourceKey(region, RESOURCE_DISK, name), disk); + return operations(region, RESOURCE_DISK, name, "CreateDisk"); + } + + public ObjectNode getDisks(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode disks = response.putArray("disks"); + listResources(region, RESOURCE_DISK).forEach(disks::add); + return response; + } + + public ObjectNode getDisk(String region, String name) { + return mapper.createObjectNode().set("disk", requireResource(region, RESOURCE_DISK, name)); + } + + public ObjectNode attachDisk(String region, JsonNode request) { + String diskName = requireText(request, "diskName"); + String instanceName = requireText(request, "instanceName"); + ObjectNode disk = requireResource(region, RESOURCE_DISK, diskName); + requireResource(region, RESOURCE_INSTANCE, instanceName); + if (disk.path("isAttached").asBoolean(false)) { + throw new AwsException("InvalidInputException", + "Disk " + diskName + " is already attached to instance " + + disk.path("attachedTo").asText() + ".", + 400); + } + disk.put("attachedTo", instanceName); + disk.put("isAttached", true); + disk.put("attachmentState", "attached"); + disk.put("state", "in-use"); + disk.put("path", request.path("diskPath").asText("/dev/xvdf")); + resourceStore.put(resourceKey(region, RESOURCE_DISK, diskName), disk); + return operations(region, RESOURCE_DISK, diskName, "AttachDisk"); + } + + public ObjectNode detachDisk(String region, String name) { + ObjectNode disk = requireResource(region, RESOURCE_DISK, name); + if (!disk.path("isAttached").asBoolean(false)) { + throw new AwsException("InvalidInputException", + "Disk " + name + " is not attached to any instance.", + 400); + } + disk.remove("attachedTo"); + disk.put("isAttached", false); + disk.put("attachmentState", "detached"); + disk.put("state", "available"); + resourceStore.put(resourceKey(region, RESOURCE_DISK, name), disk); + return operations(region, RESOURCE_DISK, name, "DetachDisk"); + } + + public ObjectNode deleteDisk(String region, String name) { + ObjectNode disk = requireResource(region, RESOURCE_DISK, name); + if (disk.path("isAttached").asBoolean(false)) { + throw new AwsException("InvalidInputException", + "Disk " + name + " is attached to instance " + disk.path("attachedTo").asText() + + " and cannot be deleted. Detach the disk first and then try again.", + 400); + } + resourceStore.delete(resourceKey(region, RESOURCE_DISK, name)); + return operations(region, RESOURCE_DISK, name, "DeleteDisk"); + } + + public ObjectNode allocateStaticIp(String region, String name) { + requireName(name, "staticIpName"); + ensureNotExists(region, RESOURCE_STATIC_IP, name); + ObjectNode ip = baseResource(region, region + "a", RESOURCE_STATIC_IP, name); + ip.put("ipAddress", publicIpFor(name)); + ip.put("isAttached", false); + resourceStore.put(resourceKey(region, RESOURCE_STATIC_IP, name), ip); + return operations(region, RESOURCE_STATIC_IP, name, "AllocateStaticIp"); + } + + public ObjectNode getStaticIps(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode ips = response.putArray("staticIps"); + listResources(region, RESOURCE_STATIC_IP).forEach(ips::add); + return response; + } + + public ObjectNode getStaticIp(String region, String name) { + return mapper.createObjectNode().set("staticIp", requireResource(region, RESOURCE_STATIC_IP, name)); + } + + public ObjectNode attachStaticIp(String region, JsonNode request) { + String staticIpName = requireText(request, "staticIpName"); + String instanceName = requireText(request, "instanceName"); + ObjectNode ip = requireResource(region, RESOURCE_STATIC_IP, staticIpName); + ObjectNode instance = requireResource(region, RESOURCE_INSTANCE, instanceName); + if (ip.path("isAttached").asBoolean(false)) { + throw new AwsException("InvalidInputException", + "StaticIp " + staticIpName + " is already attached to instance " + + ip.path("attachedTo").asText() + ".", + 400); + } + ip.put("attachedTo", instanceName); + ip.put("isAttached", true); + instance.put("publicIpAddress", ip.path("ipAddress").asText()); + instance.put("isStaticIp", true); + resourceStore.put(resourceKey(region, RESOURCE_STATIC_IP, staticIpName), ip); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, instanceName), instance); + return operations(region, RESOURCE_STATIC_IP, staticIpName, "AttachStaticIp"); + } + + public ObjectNode detachStaticIp(String region, String name) { + ObjectNode ip = requireResource(region, RESOURCE_STATIC_IP, name); + String instanceName = ip.path("attachedTo").asText(null); + if (instanceName != null) { + resourceStore.get(resourceKey(region, RESOURCE_INSTANCE, instanceName)).ifPresent(instance -> { + instance.put("isStaticIp", false); + instance.put("publicIpAddress", publicIpFor(instanceName)); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, instanceName), instance); + }); + } + ip.remove("attachedTo"); + ip.put("isAttached", false); + resourceStore.put(resourceKey(region, RESOURCE_STATIC_IP, name), ip); + return operations(region, RESOURCE_STATIC_IP, name, "DetachStaticIp"); + } + + public ObjectNode releaseStaticIp(String region, String name) { + ObjectNode ip = requireResource(region, RESOURCE_STATIC_IP, name); + String instanceName = ip.path("attachedTo").asText(null); + if (instanceName != null) { + resourceStore.get(resourceKey(region, RESOURCE_INSTANCE, instanceName)).ifPresent(instance -> { + instance.put("isStaticIp", false); + instance.put("publicIpAddress", publicIpFor(instanceName)); + resourceStore.put(resourceKey(region, RESOURCE_INSTANCE, instanceName), instance); + }); + } + resourceStore.delete(resourceKey(region, RESOURCE_STATIC_IP, name)); + return operations(region, RESOURCE_STATIC_IP, name, "ReleaseStaticIp"); + } + + public ObjectNode createKeyPair(String region, JsonNode request) { + String name = requireText(request, "keyPairName"); + ensureNotExists(region, RESOURCE_KEY_PAIR, name); + ObjectNode keyPair = keyPair(region, name, request.path("publicKeyBase64").asText(null), tags(request.path("tags"))); + resourceStore.put(resourceKey(region, RESOURCE_KEY_PAIR, name), keyPair); + + ObjectNode response = mapper.createObjectNode(); + response.set("keyPair", keyPair.deepCopy()); + response.put("publicKeyBase64", keyPair.path("publicKeyBase64").asText()); + response.put("privateKeyBase64", privateKeyBase64(name)); + response.set("operation", operation(region, RESOURCE_KEY_PAIR, name, "CreateKeyPair")); + return response; + } + + public ObjectNode importKeyPair(String region, JsonNode request) { + String name = requireText(request, "keyPairName"); + String publicKey = requireText(request, "publicKeyBase64"); + ensureNotExists(region, RESOURCE_KEY_PAIR, name); + ObjectNode keyPair = keyPair(region, name, publicKey, mapper.createArrayNode()); + resourceStore.put(resourceKey(region, RESOURCE_KEY_PAIR, name), keyPair); + return mapper.createObjectNode().set("operation", operation(region, RESOURCE_KEY_PAIR, name, "ImportKeyPair")); + } + + public ObjectNode downloadDefaultKeyPair(String region) { + String name = "LightsailDefaultKeyPair"; + resourceStore.get(resourceKey(region, RESOURCE_KEY_PAIR, name)) + .orElseGet(() -> { + ObjectNode created = keyPair(region, name, null, mapper.createArrayNode()); + resourceStore.put(resourceKey(region, RESOURCE_KEY_PAIR, name), created); + return created; + }); + ObjectNode response = mapper.createObjectNode(); + response.put("publicKeyBase64", publicKeyBase64(name)); + response.put("privateKeyBase64", privateKeyBase64(name)); + response.put("createdAt", epochSeconds(Instant.now())); + return response; + } + + public ObjectNode getKeyPairs(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode keyPairs = response.putArray("keyPairs"); + listResources(region, RESOURCE_KEY_PAIR).forEach(keyPair -> { + ObjectNode copy = keyPair.deepCopy(); + copy.remove(List.of("publicKeyBase64", "privateKeyBase64")); + keyPairs.add(copy); + }); + return response; + } + + public ObjectNode getKeyPair(String region, String name) { + ObjectNode keyPair = requireResource(region, RESOURCE_KEY_PAIR, name).deepCopy(); + keyPair.remove(List.of("publicKeyBase64", "privateKeyBase64")); + return mapper.createObjectNode().set("keyPair", keyPair); + } + + public ObjectNode deleteKeyPair(String region, String name) { + requireResource(region, RESOURCE_KEY_PAIR, name); + resourceStore.delete(resourceKey(region, RESOURCE_KEY_PAIR, name)); + return mapper.createObjectNode().set("operation", operation(region, RESOURCE_KEY_PAIR, name, "DeleteKeyPair")); + } + + public ObjectNode getRegions(JsonNode request) { + boolean includeAzs = request.path("includeAvailabilityZones").asBoolean(false); + ObjectNode response = mapper.createObjectNode(); + ArrayNode regions = response.putArray("regions"); + regions.add(regionNode("us-east-1", "Virginia", "United States", includeAzs)); + regions.add(regionNode("us-west-2", "Oregon", "United States", includeAzs)); + regions.add(regionNode("eu-central-1", "Frankfurt", "Europe", includeAzs)); + regions.add(regionNode("eu-west-1", "Ireland", "Europe", includeAzs)); + return response; + } + + public ObjectNode getBlueprints() { + ObjectNode response = mapper.createObjectNode(); + ArrayNode blueprints = response.putArray("blueprints"); + blueprints.add(blueprint("ubuntu_22_04", "Ubuntu", "linux", "Ubuntu 22.04 LTS")); + blueprints.add(blueprint("ubuntu_24_04", "Ubuntu", "linux", "Ubuntu 24.04 LTS")); + blueprints.add(blueprint("amazon_linux_2023", "Amazon Linux", "linux", "Amazon Linux 2023")); + blueprints.add(blueprint("wordpress", "WordPress", "wordpress", "WordPress")); + return response; + } + + public ObjectNode getBundles() { + ObjectNode response = mapper.createObjectNode(); + ArrayNode bundles = response.putArray("bundles"); + bundles.add(bundle("nano_3_0", "Nano", 1, 0.5, 20, 1024, 3.50)); + bundles.add(bundle("micro_3_0", "Micro", 2, 1.0, 40, 2048, 5.00)); + bundles.add(bundle("small_3_0", "Small", 2, 2.0, 60, 3072, 10.00)); + bundles.add(bundle("medium_3_0", "Medium", 2, 4.0, 80, 4096, 20.00)); + return response; + } + + public ObjectNode tagResource(String region, JsonNode request) { + String name = textOrNull(request, "resourceName"); + String arn = textOrNull(request, "resourceArn"); + ObjectNode resource = requireAnyResource(region, name, arn); + mergeTags((ArrayNode) resource.withArray("tags"), tags(request.path("tags"))); + resourceStore.put(resourceKey(region, resource.path("resourceType").asText(), resource.path("name").asText()), resource); + return operations(region, resource.path("resourceType").asText(), resource.path("name").asText(), "TagResource"); + } + + public ObjectNode untagResource(String region, JsonNode request) { + String name = textOrNull(request, "resourceName"); + String arn = textOrNull(request, "resourceArn"); + ObjectNode resource = requireAnyResource(region, name, arn); + JsonNode tagKeys = request.path("tagKeys"); + if (!tagKeys.isArray()) { + throw new AwsException("InvalidInputException", "tagKeys is required", 400); + } + ArrayNode tags = mapper.createArrayNode(); + for (JsonNode tag : resource.path("tags")) { + if (!containsText(tagKeys, tag.path("key").asText())) { + tags.add(tag.deepCopy()); + } + } + resource.set("tags", tags); + resourceStore.put(resourceKey(region, resource.path("resourceType").asText(), resource.path("name").asText()), resource); + return operations(region, resource.path("resourceType").asText(), resource.path("name").asText(), "UntagResource"); + } + + public ObjectNode getActiveNames(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode names = response.putArray("activeNames"); + listResources(region, null).stream() + .map(resource -> resource.path("name").asText()) + .sorted() + .forEach(names::add); + return response; + } + + public ObjectNode getOperations(String region) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode operations = response.putArray("operations"); + listOperations(region).forEach(operations::add); + return response; + } + + public ObjectNode getOperationsForResource(String region, String resourceName) { + ObjectNode response = mapper.createObjectNode(); + ArrayNode operations = response.putArray("operations"); + listOperations(region).stream() + .filter(operation -> resourceName.equals(operation.path("resourceName").asText())) + .forEach(operations::add); + return response; + } + + public ObjectNode getOperation(String region, String operationId) { + return mapper.createObjectNode().set("operation", operationStore.get(operationKey(region, operationId)) + .orElseThrow(() -> new AwsException("NotFoundException", "Operation " + operationId + " was not found", 400))); + } + + public ObjectNode emptyList(String fieldName) { + ObjectNode response = mapper.createObjectNode(); + response.set(fieldName, mapper.createArrayNode()); + return response; + } + + public ObjectNode isVpcPeered() { + return mapper.createObjectNode().put("isPeered", false); + } + + private ObjectNode baseResource(String region, String availabilityZone, String resourceType, String name) { + Instant now = Instant.now(); + ObjectNode resource = mapper.createObjectNode(); + resource.put("name", name); + resource.put("arn", arn(region, resourceType, name)); + resource.put("supportCode", region + "/" + name); + resource.put("createdAt", epochSeconds(now)); + resource.set("location", location(region, availabilityZone)); + resource.put("resourceType", resourceType); + return resource; + } + + private ObjectNode operation(String region, String resourceType, String resourceName, String operationType) { + Instant now = Instant.now(); + String id = UUID.randomUUID().toString(); + ObjectNode operation = mapper.createObjectNode(); + operation.put("id", id); + operation.put("resourceName", resourceName); + operation.put("resourceType", resourceType); + operation.put("createdAt", epochSeconds(now)); + operation.set("location", location(region, region + "a")); + operation.put("isTerminal", true); + operation.put("operationDetails", operationType + " completed locally"); + operation.put("operationType", operationType); + operation.put("status", "Succeeded"); + operation.put("statusChangedAt", epochSeconds(now)); + operationStore.put(operationKey(region, id), operation); + return operation; + } + + private ObjectNode operations(String region, String resourceType, String resourceName, String operationType) { + ObjectNode response = mapper.createObjectNode(); + response.putArray("operations").add(operation(region, resourceType, resourceName, operationType)); + return response; + } + + private ObjectNode requireResource(String region, String resourceType, String name) { + requireName(name, "resourceName"); + return resourceStore.get(resourceKey(region, resourceType, name)) + .orElseThrow(() -> new AwsException("NotFoundException", + resourceType + " " + name + " was not found", 400)); + } + + private ObjectNode requireAnyResource(String region, String name, String arn) { + if (arn != null && !arn.isBlank()) { + return listResources(region, null).stream() + .filter(resource -> arn.equals(resource.path("arn").asText())) + .findFirst() + .orElseThrow(() -> new AwsException("NotFoundException", "Resource " + arn + " was not found", 400)); + } + if (name == null || name.isBlank()) { + throw new AwsException("InvalidInputException", "resourceName is required", 400); + } + return listResources(region, null).stream() + .filter(resource -> name.equals(resource.path("name").asText())) + .findFirst() + .orElseThrow(() -> new AwsException("NotFoundException", "Resource " + name + " was not found", 400)); + } + + private List listResources(String region, String resourceType) { + String prefix = region + ":"; + return resourceStore.scan(key -> key.startsWith(prefix) + && (resourceType == null || key.startsWith(resourceKeyPrefix(region, resourceType)))) + .stream() + .map(ObjectNode::deepCopy) + .sorted(Comparator.comparing(node -> node.path("name").asText())) + .toList(); + } + + private List listOperations(String region) { + String prefix = region + ":"; + return operationStore.scan(key -> key.startsWith(prefix)).stream() + .map(ObjectNode::deepCopy) + .sorted(Comparator.comparing(node -> node.path("createdAt").asDouble())) + .toList(); + } + + private void ensureNotExists(String region, String resourceType, String name) { + if (resourceStore.get(resourceKey(region, resourceType, name)).isPresent()) { + throw new AwsException("InvalidInputException", resourceType + " " + name + " already exists", 400); + } + } + + private void detachStaticIpsFrom(String instanceName) { + for (String key : new ArrayList<>(resourceStore.keys())) { + if (key.contains(":" + RESOURCE_STATIC_IP + ":")) { + resourceStore.get(key).ifPresent(ip -> { + if (instanceName.equals(ip.path("attachedTo").asText(null))) { + ip.remove("attachedTo"); + ip.put("isAttached", false); + resourceStore.put(key, ip); + } + }); + } + } + } + + private void detachDisksFrom(String instanceName) { + for (String key : new ArrayList<>(resourceStore.keys())) { + if (key.contains(":" + RESOURCE_DISK + ":")) { + resourceStore.get(key).ifPresent(disk -> { + if (instanceName.equals(disk.path("attachedTo").asText(null))) { + disk.remove("attachedTo"); + disk.put("isAttached", false); + disk.put("attachmentState", "detached"); + disk.put("state", "available"); + resourceStore.put(key, disk); + } + }); + } + } + } + + private ObjectNode keyPair(String region, String name, String publicKeyBase64, ArrayNode tags) { + ObjectNode keyPair = baseResource(region, region + "a", RESOURCE_KEY_PAIR, name); + keyPair.set("tags", tags); + keyPair.put("fingerprint", Base64.getEncoder().encodeToString(("fingerprint:" + name).getBytes(StandardCharsets.UTF_8))); + keyPair.put("publicKeyBase64", publicKeyBase64 == null ? publicKeyBase64(name) : publicKeyBase64); + return keyPair; + } + + private ObjectNode regionNode(String name, String displayName, String continentCode, boolean includeAzs) { + ObjectNode region = mapper.createObjectNode(); + region.put("continentCode", continentCode); + region.put("description", displayName); + region.put("displayName", displayName); + region.put("name", name); + if (includeAzs) { + ArrayNode zones = region.putArray("availabilityZones"); + zones.add(availabilityZone(name + "a", name)); + zones.add(availabilityZone(name + "b", name)); + region.set("relationalDatabaseAvailabilityZones", zones.deepCopy()); + } + return region; + } + + private ObjectNode availabilityZone(String zoneName, String regionName) { + return mapper.createObjectNode() + .put("zoneName", zoneName) + .put("state", "available") + .put("regionName", regionName); + } + + private ObjectNode blueprint(String id, String name, String group, String description) { + return mapper.createObjectNode() + .put("blueprintId", id) + .put("name", name) + .put("group", group) + .put("type", "os") + .put("description", description) + .put("isActive", true) + .put("minPower", 0) + .put("version", "latest") + .put("versionCode", "1") + .put("productUrl", "https://aws.amazon.com/lightsail/") + .put("platform", "LINUX_UNIX") + .put("appCategory", "LfR"); + } + + private ObjectNode bundle(String id, String name, int cpu, double ram, int disk, int transfer, double price) { + ObjectNode bundle = mapper.createObjectNode(); + bundle.put("price", price); + bundle.put("cpuCount", cpu); + bundle.put("diskSizeInGb", disk); + bundle.put("bundleId", id); + bundle.put("instanceType", "lightsail." + id); + bundle.put("isActive", true); + bundle.put("name", name); + bundle.put("power", cpu * 100); + bundle.put("ramSizeInGb", ram); + bundle.put("transferPerMonthInGb", transfer); + bundle.putArray("supportedPlatforms").add("LINUX_UNIX").add("WINDOWS"); + bundle.putArray("supportedAppCategories").add("LfR"); + bundle.put("publicIpv4AddressCount", 1); + return bundle; + } + + private ObjectNode hardware(String bundleId) { + ObjectNode hardware = mapper.createObjectNode(); + int cpu = switch (bundleId) { + case "nano_3_0" -> 1; + default -> 2; + }; + double ram = switch (bundleId) { + case "nano_3_0" -> 0.5; + case "micro_3_0" -> 1.0; + case "small_3_0" -> 2.0; + case "medium_3_0" -> 4.0; + default -> 1.0; + }; + hardware.put("cpuCount", cpu); + hardware.put("disks", mapper.createArrayNode()); + hardware.put("ramSizeInGb", ram); + return hardware; + } + + private ObjectNode defaultNetworking() { + ObjectNode networking = mapper.createObjectNode(); + ArrayNode ports = networking.putArray("ports"); + ObjectNode ssh = mapper.createObjectNode(); + ssh.put("fromPort", 22); + ssh.put("toPort", 22); + ssh.put("protocol", "tcp"); + ssh.putArray("cidrs").add("0.0.0.0/0"); + ssh.putArray("ipv6Cidrs"); + ssh.putArray("cidrListAliases"); + ports.add(ssh); + networking.put("monthlyTransfer", mapper.createObjectNode() + .put("gbPerMonthAllocated", 1024)); + return networking; + } + + private ObjectNode instanceState(String state) { + ObjectNode node = mapper.createObjectNode(); + node.put("name", state); + node.put("code", "running".equals(state) ? 16 : 80); + return node; + } + + private ObjectNode location(String region, String availabilityZone) { + return mapper.createObjectNode() + .put("availabilityZone", availabilityZone) + .put("regionName", region); + } + + private ArrayNode tags(JsonNode tagsNode) { + ArrayNode tags = mapper.createArrayNode(); + if (tagsNode != null && tagsNode.isArray()) { + for (JsonNode tag : tagsNode) { + String key = textOrNull(tag, "key"); + if (key == null) { + key = textOrNull(tag, "Key"); + } + if (key != null) { + ObjectNode tagNode = mapper.createObjectNode(); + tagNode.put("key", key); + String value = textOrNull(tag, "value"); + if (value == null) { + value = textOrNull(tag, "Value"); + } + if (value != null) { + tagNode.put("value", value); + } + tags.add(tagNode); + } + } + } + return tags; + } + + private void mergeTags(ArrayNode existing, ArrayNode updates) { + for (JsonNode update : updates) { + String key = update.path("key").asText(); + boolean replaced = false; + for (int i = 0; i < existing.size(); i++) { + if (key.equals(existing.get(i).path("key").asText())) { + existing.set(i, update.deepCopy()); + replaced = true; + break; + } + } + if (!replaced) { + existing.add(update.deepCopy()); + } + } + } + + private boolean samePort(JsonNode left, JsonNode right) { + return left.path("fromPort").asInt(-1) == right.path("fromPort").asInt(-2) + && left.path("toPort").asInt(-1) == right.path("toPort").asInt(-2) + && left.path("protocol").asText("").equals(right.path("protocol").asText("")); + } + + private boolean containsText(JsonNode array, String value) { + for (JsonNode node : array) { + if (value.equals(node.asText())) { + return true; + } + } + return false; + } + + private String arn(String region, String resourceType, String name) { + return regionResolver.buildArn("lightsail", region, resourceType + "/" + name); + } + + private static String requireText(JsonNode request, String field) { + String value = request.path(field).asText(null); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidInputException", field + " is required", 400); + } + return value; + } + + private static void requireArray(JsonNode request, String field) { + if (!request.has(field) || !request.path(field).isArray() || request.path(field).isEmpty()) { + throw new AwsException("InvalidInputException", field + " is required", 400); + } + } + + private static void requireName(String name, String field) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidInputException", field + " is required", 400); + } + } + + private static String textOrNull(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + return value == null || value.isNull() ? null : value.asText(); + } + + private static String resourceKey(String region, String resourceType, String name) { + return resourceKeyPrefix(region, resourceType) + name; + } + + private static String resourceKeyPrefix(String region, String resourceType) { + return region + ":" + resourceType + ":"; + } + + private static String operationKey(String region, String operationId) { + return region + ":" + operationId; + } + + private static double epochSeconds(Instant instant) { + return instant.toEpochMilli() / 1000.0; + } + + private static String privateIpFor(String name) { + int value = Math.floorMod(name.hashCode(), 200) + 20; + return "10.0.0." + value; + } + + private static String publicIpFor(String name) { + int value = Math.floorMod(name.hashCode(), 200) + 20; + return "203.0.113." + value; + } + + private static String blueprintName(String blueprintId) { + return switch (blueprintId) { + case "ubuntu_24_04" -> "Ubuntu 24.04 LTS"; + case "ubuntu_22_04" -> "Ubuntu 22.04 LTS"; + case "amazon_linux_2023" -> "Amazon Linux 2023"; + case "wordpress" -> "WordPress"; + default -> blueprintId; + }; + } + + private static String defaultUsername(String blueprintId) { + return blueprintId != null && blueprintId.startsWith("amazon_linux") ? "ec2-user" : "ubuntu"; + } + + private static String publicKeyBase64(String name) { + return Base64.getEncoder().encodeToString(("ssh-rsa FLOCI-" + name).getBytes(StandardCharsets.UTF_8)); + } + + private static String privateKeyBase64(String name) { + return Base64.getEncoder().encodeToString(("-----BEGIN PRIVATE KEY-----\nfloci-" + name + + "\n-----END PRIVATE KEY-----\n").getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 830ae55d88..2a560042f9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -107,6 +107,8 @@ floci: flush-interval-ms: 5000 batch: flush-interval-ms: 5000 + lightsail: + flush-interval-ms: 5000 codepipeline: flush-interval-ms: 5000 s3vectors: @@ -411,6 +413,7 @@ floci: emit-mode: synchronous cloudtrail: enabled: true + lightsail: cloudcontrol: enabled: true cloudfront: diff --git a/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailIntegrationTest.java new file mode 100644 index 0000000000..adb237c56d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailIntegrationTest.java @@ -0,0 +1,497 @@ +package io.github.hectorvent.floci.services.lightsail; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; + +@QuarkusTest +class LightsailIntegrationTest { + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET_PREFIX = "Lightsail_20161128."; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void instanceDiskAndStaticIpLifecycleRoundTripsThroughJsonHandler() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetBlueprints") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("blueprints", hasSize(4)) + .body("blueprints[0].blueprintId", equalTo("ubuntu_22_04")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateInstances") + .contentType(CONTENT_TYPE) + .body(""" + { + "instanceNames": ["web-a"], + "availabilityZone": "us-east-1a", + "blueprintId": "ubuntu_22_04", + "bundleId": "nano_3_0", + "tags": [{"key": "component", "value": "web"}] + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations", hasSize(1)) + .body("operations[0].operationType", equalTo("CreateInstance")) + .body("operations[0].status", equalTo("Succeeded")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetInstance") + .contentType(CONTENT_TYPE) + .body(""" + {"instanceName": "web-a"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("instance.name", equalTo("web-a")) + .body("instance.arn", startsWith("arn:aws:lightsail:")) + .body("instance.state.name", equalTo("running")) + .body("instance.tags[0].key", equalTo("component")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "StopInstance") + .contentType(CONTENT_TYPE) + .body(""" + {"instanceName": "web-a"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("StopInstance")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetInstanceState") + .contentType(CONTENT_TYPE) + .body(""" + {"instanceName": "web-a"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("state.name", equalTo("stopped")) + .body("state.code", equalTo(80)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateDisk") + .contentType(CONTENT_TYPE) + .body(""" + { + "diskName": "web-data", + "availabilityZone": "us-east-1a", + "sizeInGb": 8 + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("CreateDisk")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachDisk") + .contentType(CONTENT_TYPE) + .body(""" + { + "diskName": "web-data", + "instanceName": "web-a", + "diskPath": "/dev/xvdf" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("AttachDisk")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetDisk") + .contentType(CONTENT_TYPE) + .body(""" + {"diskName": "web-data"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("disk.name", equalTo("web-data")) + .body("disk.attachedTo", equalTo("web-a")) + .body("disk.isAttached", equalTo(true)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AllocateStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + {"staticIpName": "web-ip"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("AllocateStaticIp")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + { + "staticIpName": "web-ip", + "instanceName": "web-a" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("AttachStaticIp")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + {"staticIpName": "web-ip"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("staticIp.name", equalTo("web-ip")) + .body("staticIp.attachedTo", equalTo("web-a")) + .body("staticIp.isAttached", equalTo(true)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetOperationsForResource") + .contentType(CONTENT_TYPE) + .body(""" + {"resourceName": "web-a"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations", hasSize(2)) + .body("operations[0].id", notNullValue()); + } + + @Test + void keyPairsTagsRegionsAndUnsupportedOperationsUseAwsJsonShape() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateKeyPair") + .contentType(CONTENT_TYPE) + .body(""" + { + "keyPairName": "deployer", + "tags": [{"key": "owner", "value": "platform"}] + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("keyPair.name", equalTo("deployer")) + .body("publicKeyBase64", notNullValue()) + .body("privateKeyBase64", notNullValue()) + .body("operation.operationType", equalTo("CreateKeyPair")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "TagResource") + .contentType(CONTENT_TYPE) + .body(""" + { + "resourceName": "deployer", + "tags": [{"key": "env", "value": "test"}] + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("TagResource")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetKeyPair") + .contentType(CONTENT_TYPE) + .body(""" + {"keyPairName": "deployer"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("keyPair.name", equalTo("deployer")) + .body("keyPair.tags", hasSize(2)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetRegions") + .contentType(CONTENT_TYPE) + .body(""" + {"includeAvailabilityZones": true} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("regions", hasSize(4)) + .body("regions[0].availabilityZones", hasSize(2)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetBuckets") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("buckets", hasSize(0)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateContainerService") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("UnsupportedOperation")) + .body("message", equalTo("Operation CreateContainerService is recognized by Amazon Lightsail but is not implemented in Floci.")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "NotARealAction") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")) + .body("message", equalTo("Unknown operation NotARealAction")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetKeyPair") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidInputException")) + .body("message", equalTo("keyPairName is required")); + } + + @Test + void diskStaticIpAndHardwareEdgeCasesMatchLightsailBehavior() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateInstances") + .contentType(CONTENT_TYPE) + .body(""" + { + "instanceNames": ["review-web"], + "availabilityZone": "us-east-1a", + "blueprintId": "ubuntu_22_04", + "bundleId": "medium_3_0" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetInstance") + .contentType(CONTENT_TYPE) + .body(""" + {"instanceName": "review-web"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("instance.hardware.cpuCount", equalTo(2)) + .body("instance.hardware.ramSizeInGb", equalTo(4.0f)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateInstances") + .contentType(CONTENT_TYPE) + .body(""" + { + "instanceNames": ["review-web-b"], + "availabilityZone": "us-east-1a", + "blueprintId": "ubuntu_22_04", + "bundleId": "micro_3_0" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "CreateDisk") + .contentType(CONTENT_TYPE) + .body(""" + { + "diskName": "review-data", + "availabilityZone": "us-east-1a", + "sizeInGb": 8 + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachDisk") + .contentType(CONTENT_TYPE) + .body(""" + { + "diskName": "review-data", + "instanceName": "review-web" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachDisk") + .contentType(CONTENT_TYPE) + .body(""" + { + "diskName": "review-data", + "instanceName": "review-web-b" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteDisk") + .contentType(CONTENT_TYPE) + .body(""" + {"diskName": "review-data"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DetachDisk") + .contentType(CONTENT_TYPE) + .body(""" + {"diskName": "review-data"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DetachDisk") + .contentType(CONTENT_TYPE) + .body(""" + {"diskName": "review-data"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AllocateStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + {"staticIpName": "review-ip"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + { + "staticIpName": "review-ip", + "instanceName": "review-web" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "AttachStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + { + "staticIpName": "review-ip", + "instanceName": "review-web-b" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "ReleaseStaticIp") + .contentType(CONTENT_TYPE) + .body(""" + {"staticIpName": "review-ip"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations[0].operationType", equalTo("ReleaseStaticIp")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetOperationsForResource") + .contentType(CONTENT_TYPE) + .body(""" + {"resourceName": "review-ip"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("operations.operationType", hasItems("AllocateStaticIp", "AttachStaticIp", "ReleaseStaticIp")) + .body("operations.operationType", not(hasItem("DetachStaticIp"))); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 36c46fc2b2..99a5d9974b 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -38,6 +38,8 @@ floci: flush-interval-ms: 60000 batch: flush-interval-ms: 60000 + lightsail: + flush-interval-ms: 60000 codepipeline: flush-interval-ms: 60000 s3vectors: @@ -258,6 +260,7 @@ floci: emit-mode: off cloudtrail: enabled: true + lightsail: cloudcontrol: enabled: true cloudfront: diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index debcbb0d9c..000f99f9e2 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -111,6 +111,7 @@ deferred_handlers: - { path: src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java } # sts (lives in iam package); single-table, registerable next + - { path: src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailJsonHandler.java } # non-tabular doc (grouped/inline); standalone action table to be added - { path: src/main/java/io/github/hectorvent/floci/services/pricing/PricingJsonHandler.java } # no standalone action table yet - { path: src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java } # mixed-mode (Query + REST surface)