Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(dsql): add Aurora DSQL's control plane and AWS::DSQL::Cluster (#6048)

Alessandro Lattao95bf6df47454
diff --git a/README.md b/README.md
index afcfa3f111..5303fc307b 100644
--- a/README.md
+++ b/README.md
@@ -298,7 +298,7 @@ Floci supports local emulation for application services, data services, eventing
| API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator |
| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Redshift Serverless, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker |
-| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, DMS, MemoryDB, ElastiCache, Timestream for InfluxDB |
+| Databases and caching | Aurora DSQL, RDS, RDS Data API, Neptune, DocumentDB, DMS, MemoryDB, ElastiCache, Timestream for InfluxDB |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations |
| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Pricing Calculator, BCM Data Exports |
@@ -337,6 +337,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| CloudWatch OAM | In-process | Full 15-operation sink, policy, cross-account link, and tagging API |
| ElastiCache | Real Docker | Redis / Valkey protocol, IAM auth, SigV4 validation |
| MemoryDB | Real Docker | Redis / Valkey protocol via real containers; JSON 1.1 control plane; reuses ElastiCache RESP proxy |
+| Aurora DSQL | In-process | Control plane and `AWS::DSQL::Cluster`: clusters, policies, tags; clusters have no database behind them |
| RDS | Real Docker | PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines |
| Timestream for InfluxDB | Real Docker, mock mode available | InfluxDB 2.x DB instances and read replica clusters via `influxdb:2.7`; initial auth secret in Secrets Manager; backups and restore through the influx CLI |
| RDS Data API | REST JSON over real RDS containers | Raw SQL execution and transactions for local MySQL / MariaDB RDS resources |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 3985975b84..ff02accc98 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -239,6 +239,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>rds</artifactId>
</dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>dsql</artifactId>
+ </dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>neptune</artifactId>
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 2229a16c6d..9f405659a4 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
@@ -50,6 +50,7 @@ import software.amazon.awssdk.services.databasemigration.DatabaseMigrationClient
import software.amazon.awssdk.services.datasync.DataSyncClient;
import software.amazon.awssdk.services.detective.DetectiveClient;
import software.amazon.awssdk.services.dlm.DlmClient;
+import software.amazon.awssdk.services.dsql.DsqlClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient;
import software.amazon.awssdk.services.ec2.Ec2Client;
@@ -1288,6 +1289,14 @@ public final class TestFixtures {
: hostedZoneId;
}
+ public static DsqlClient dsqlClient() {
+ return DsqlClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static RdsClient rdsClient() {
return RdsClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java
new file mode 100644
index 0000000000..425d065041
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java
@@ -0,0 +1,110 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+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 software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.dsql.DsqlClient;
+import software.amazon.awssdk.services.dsql.model.ClusterStatus;
+import software.amazon.awssdk.services.dsql.model.CreateClusterResponse;
+import software.amazon.awssdk.services.dsql.model.GetClusterPolicyResponse;
+import software.amazon.awssdk.services.dsql.model.GetClusterResponse;
+import software.amazon.awssdk.services.dsql.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dsql.model.ValidationException;
+
+import java.time.Duration;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Aurora DSQL's control plane through the real AWS SDK and its waiters: a cluster created,
+ * described, listed, tagged, protected from deletion, given a policy and deleted.
+ */
+@DisplayName("Aurora DSQL")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class DsqlCompatTest {
+
+ private static final Region REGION = TestFixtures.region();
+ private static final Duration WAIT_TIMEOUT =
+ TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofSeconds(10);
+
+ private static DsqlClient dsql;
+ private static String identifier;
+
+ @BeforeAll
+ static void createCluster() {
+ dsql = TestFixtures.dsqlClient();
+ CreateClusterResponse created = dsql.createCluster(b -> b
+ .deletionProtectionEnabled(false)
+ .tags(Map.of("Name", TestFixtures.uniqueName("dsql-compat"))));
+ identifier = created.identifier();
+ assertThat(created.status()).isEqualTo(ClusterStatus.CREATING);
+
+ dsql.waiter().waitUntilClusterActive(b -> b.identifier(identifier), w -> w.waitTimeout(WAIT_TIMEOUT));
+ }
+
+ @AfterAll
+ static void deleteCluster() {
+ if (identifier == null) {
+ return;
+ }
+ dsql.deleteCluster(b -> b.identifier(identifier));
+ dsql.waiter().waitUntilClusterNotExists(b -> b.identifier(identifier), w -> w.waitTimeout(WAIT_TIMEOUT));
+ dsql.close();
+ }
+
+ @Test
+ @Order(1)
+ void aClusterIsActiveWithItsEndpointAndTags() {
+ GetClusterResponse cluster = dsql.getCluster(b -> b.identifier(identifier));
+
+ assertThat(identifier).matches("[a-z2-7]{26}");
+ assertThat(cluster.status()).isEqualTo(ClusterStatus.ACTIVE);
+ assertThat(cluster.deletionProtectionEnabled()).isFalse();
+ assertThat(cluster.endpoint()).startsWith(identifier + ".dsql." + REGION.id() + ".");
+ assertThat(cluster.arn()).endsWith(":cluster/" + identifier);
+ assertThat(dsql.listClusters(b -> { }).clusters())
+ .anySatisfy(summary -> assertThat(summary.identifier()).isEqualTo(identifier));
+ assertThat(dsql.listTagsForResource(b -> b.resourceArn(cluster.arn())).tags()).containsKey("Name");
+ }
+
+ @Test
+ @Order(2)
+ void aProtectedClusterIsNotDeleted() {
+ dsql.updateCluster(b -> b.identifier(identifier).deletionProtectionEnabled(true));
+
+ assertThatThrownBy(() -> dsql.deleteCluster(b -> b.identifier(identifier)))
+ .isInstanceOf(ValidationException.class)
+ .hasMessageContaining("Deletion protection is enabled");
+
+ dsql.updateCluster(b -> b.identifier(identifier).deletionProtectionEnabled(false));
+ }
+
+ @Test
+ @Order(3)
+ void aPolicyIsKeptInDsqlsFormAndAPublicOneRefused() {
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":"
+ + "{\"AWS\":\"*\"},\"Action\":[\"dsql:DbConnect\"],\"Resource\":\"*\",\"Condition\":"
+ + "{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}}]}";
+
+ String version = dsql.putClusterPolicy(b -> b.identifier(identifier).policy(policy)).policyVersion();
+ GetClusterPolicyResponse kept = dsql.getClusterPolicy(b -> b.identifier(identifier));
+ assertThat(version).matches("\\d{13}");
+ assertThat(kept.policyVersion()).isEqualTo(version);
+ assertThat(kept.policy()).contains("\"Action\" : \"dsql:DbConnect\"");
+ assertThatThrownBy(() -> dsql.putClusterPolicy(b -> b.identifier(identifier).policy(
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","
+ + "\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}]}")))
+ .isInstanceOf(ValidationException.class)
+ .hasMessageContaining("it grants public access");
+ assertThat(dsql.deleteClusterPolicy(b -> b.identifier(identifier)).policyVersion()).isEqualTo(version);
+ assertThatThrownBy(() -> dsql.getClusterPolicy(b -> b.identifier(identifier)))
+ .isInstanceOf(ResourceNotFoundException.class);
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 544f4991cd..584783270e 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -185,6 +185,7 @@ cross-resource references.
| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` |
| EKS | `Cluster`, `Nodegroup` |
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
+| Aurora DSQL | `Cluster` |
| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) |
| Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |
diff --git a/docs/services/dsql.md b/docs/services/dsql.md
new file mode 100644
index 0000000000..3c58ea9e34
--- /dev/null
+++ b/docs/services/dsql.md
@@ -0,0 +1,86 @@
+# Aurora DSQL
+
+**Protocol:** REST JSON
+
+**Endpoint:** `http://localhost:4566`
+
+Floci serves Aurora DSQL's control plane and `AWS::DSQL::Cluster`. A cluster has no database
+behind it here: it is `ACTIVE` as soon as it is created, and its endpoint is named as on AWS but
+not served. The answers and messages below were measured on AWS.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `CreateCluster` | Creates a cluster, `CREATING` in the answer and `ACTIVE` right after, or `PENDING_SETUP` for a multi-Region one; deletion protection is on unless turned off |
+| `ListClusters` | Lists the Region's clusters, paginated |
+| `GetCluster` | Returns a cluster, its endpoint and encryption details |
+| `UpdateCluster` | Changes deletion protection, the KMS key and the multi-Region properties |
+| `DeleteCluster` | Deletes a cluster, `DELETING` in the answer or `PENDING_DELETE` for a multi-Region one; refused while deletion protection is on |
+| `GetVpcEndpointServiceName` | Returns the Region's VPC endpoint service name |
+| `PutClusterPolicy` | Sets the cluster's resource policy once it passes DSQL's checks, with optimistic versioning |
+| `GetClusterPolicy` | Returns the resource policy in DSQL's form, and its version |
+| `DeleteClusterPolicy` | Removes the resource policy, answering the version removed |
+<!-- floci:actions:end -->
+
+`TagResource`, `UntagResource` and `ListTagsForResource` work on cluster ARNs. As on AWS, an ARN
+that is not a well-formed cluster ARN is refused with `AccessDeniedException`, one of another
+Region with `BadRequestException`, and one of no cluster with `NotFoundException`. Cluster
+identifiers are 26 characters of lowercase base32, as DSQL's are, and invalid ones are refused with
+DSQL's messages. A cluster's endpoint is `<cluster-id>.dsql.<region>.localhost.floci.io`.
+
+A cluster created with a witness Region is `PENDING_SETUP`, and lists itself among its clusters.
+Once it and each peer it is updated with name one another, all of them are `ACTIVE`, as on AWS,
+where this takes about two minutes. Nothing is replicated between them. A customer-managed KMS key
+is recorded and reported; nothing is encrypted with it.
+
+## Cluster policies
+
+`PutClusterPolicy`, and `CreateCluster` with a `policy`, check the document as DSQL does and refuse
+it with DSQL's messages:
+
+- JSON that does not parse, and a statement with no `Principal` or `Resource`, or with
+ `NotPrincipal` or `NotResource`;
+- a document missing or misusing an element: no `Statement`, a `Version` other than `2008-10-17`
+ or `2012-10-17`, a member of no policy grammar, an `Effect` other than `Allow` or `Deny`, an
+ unknown condition operator (operators are matched as written), and a principal that names no one:
+ an IAM role or user is looked up in its account, and an account is always taken to exist;
+- a service principal;
+- an `Allow` to everyone (`"*"` or an `AWS` `"*"`) that no condition restricts. A condition
+ restricts with one of the trusted keys of DSQL's
+ [block public access](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/rbp-block-public-access.html)
+ page, or `aws:SourceIp`, `aws:SourceVpcArn`, `aws:VpceAccount`, `aws:VpceOrgID` or
+ `aws:VpceOrgPaths`, which DSQL also accepts: under a string equality, or a pattern without a
+ wildcard (for an ARN, without one in the account), and never with a policy variable; with an
+ `aws:SourceIp` prefix of at least /8 for IPv4 or /32 for IPv6; or with
+ `aws:PrincipalIsAWSService` true. `IfExists`, `ForAllValues:` and negated operators never
+ restrict;
+- a policy that explicitly denies the caller both `dsql:PutClusterPolicy` and
+ `dsql:DeleteClusterPolicy`, unless `bypassPolicyLockoutSafetyCheck` is true.
+
+The policy is kept and returned in DSQL's form: pretty-printed, its elements in DSQL's order, a
+list of one value written as that value, condition values as text, an account id as its root ARN,
+and `2008-10-17` when it has no `Version`. A policy's version is the time it was set, in epoch
+milliseconds. Cluster policies are not enforced: Floci's IAM enforcement does not cover DSQL.
+
+## CloudFormation
+
+`AWS::DSQL::Cluster` waits for `ACTIVE`, or `PENDING_SETUP` for a multi-Region cluster. `Ref`
+returns the identifier; `Fn::GetAtt` supports `Identifier`, `ResourceArn`, `Status`, `CreationTime`,
+`Endpoint`, `VpcEndpoint`, `VpcEndpointServiceName` and, while the cluster has a policy,
+`PolicyVersion`. Properties are checked against the resource schema's types, as on AWS (a
+`PolicyDocument` is text). An update leaves a property the template no longer sets as it was,
+deletion protection included, but removes the tags and the policy it no longer sets; a policy the
+template does not change keeps its version. A protected cluster makes the stack's deletion fail, as
+on AWS.
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_DSQL_ENABLED` | `true` | Enable or disable Aurora DSQL |
+| `FLOCI_SERVICES_DSQL_ENDPOINT_SUFFIX` | `localhost.floci.io` | Domain the endpoints are named under, `<cluster-id>.dsql.<region>.<suffix>` |
+
+See the [Aurora DSQL API Reference](https://docs.aws.amazon.com/aurora-dsql/latest/APIReference/Welcome.html)
+and the [Aurora DSQL User Guide](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/what-is-aurora-dsql.html).
diff --git a/docs/services/index.md b/docs/services/index.md
index a0cd03fbaa..869276a62f 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -63,6 +63,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 30 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
+| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` | REST JSON | 9 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 105 |
| [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 |
| [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 |
diff --git a/mkdocs.yml b/mkdocs.yml
index 753919e89d..15607f3225 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -140,6 +140,7 @@ nav:
- AWS Service Catalog: services/service-catalog.md
- ElastiCache: services/elasticache.md
- MemoryDB: services/memorydb.md
+ - Aurora DSQL: services/dsql.md
- RDS: services/rds.md
- RDS Data API: services/rds-data.md
- Timestream for InfluxDB: services/timestream-influxdb.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 07035b12a6..2d30c5bf46 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -743,6 +743,7 @@ public interface EmulatorConfig {
RdsServiceConfig rds();
RedshiftServiceConfig redshift();
RdsDataServiceConfig rdsData();
+ DsqlServiceConfig dsql();
RedshiftDataServiceConfig redshiftData();
RedshiftServerlessServiceConfig redshiftServerless();
EventBridgeServiceConfig eventbridge();
@@ -1763,6 +1764,19 @@ public interface EmulatorConfig {
int auroraResumeDelayMillis();
}
+ interface DsqlServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ /**
+ * Domain under which cluster endpoints are named, {@code <id>.dsql.<region>.<suffix>}. The
+ * default resolves to the loopback address on the host and to Floci inside its Docker
+ * network.
+ */
+ @WithDefault("localhost.floci.io")
+ String endpointSuffix();
+ }
+
interface RdsDataServiceConfig {
@WithDefault("true")
boolean enabled();
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 cb5c635984..8d537ccb58 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
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.controltower.ControlTowerControlContr
import io.github.hectorvent.floci.services.controltower.ControlTowerController;
import io.github.hectorvent.floci.services.detective.DetectiveController;
import io.github.hectorvent.floci.services.dlm.DlmController;
+import io.github.hectorvent.floci.services.dsql.DsqlController;
import io.github.hectorvent.floci.services.efs.EfsController;
import io.github.hectorvent.floci.services.eks.EksController;
import io.github.hectorvent.floci.services.fis.FisController;
@@ -200,6 +201,10 @@ public class ResolvedServiceCatalog {
null, null, 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("rds-data"), Set.of(), Set.of(RdsDataController.class)),
+ descriptor("dsql", "dsql", config.services().dsql().enabled(), true,
+ "dsql", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("dsql"), Set.of(), Set.of(DsqlController.class)),
descriptor("neptune", "neptune", config.services().neptune().enabled(), true,
"neptune", storageMode(config.storage().services().neptune().mode(), config.storage().mode()),
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisioner.java
new file mode 100644
index 0000000000..bc4ba8a4d8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisioner.java
@@ -0,0 +1,163 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.dsql.DsqlService;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::DSQL::Cluster}. {@code Ref} is the cluster's
+ * identifier, the schema's primary identifier, and every read-only property but
+ * {@code EncryptionDetails}, an object, is an attribute. Properties are read against the resource
+ * schema, so a value of the wrong type fails the resource as on AWS. As CloudFormation's handler
+ * does, create waits for the cluster to be ACTIVE, or PENDING_SETUP for a multi-Region one, and an
+ * update leaves a property the template no longer sets as it was, but for the tags and the policy,
+ * which go (measured, eu-west-1, 2026-10-20).
+ */
+@ApplicationScoped
+public class DsqlCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String TYPE = "AWS::DSQL::Cluster";
+ private static final Duration READY_TIMEOUT = Duration.ofMinutes(5);
+ /** Measured: {@code 2026-10-16T15:49:38.488Z}, milliseconds always written. */
+ private static final DateTimeFormatter CREATION_TIME =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
+ private static final Set<String> SETTLED = Set.of("ACTIVE", "PENDING_SETUP");
+
+ private final DsqlService dsqlService;
+
+ @Inject
+ public DsqlCfnProvisioner(DsqlService dsqlService) {
+ this.dsqlService = dsqlService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
+ String region = ctx.region();
+ CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(ctx.engine());
+ JsonNode protection = read(types, props, "DeletionProtectionEnabled");
+ JsonNode kmsKey = read(types, props, "KmsEncryptionKey");
+ JsonNode multiRegion = read(types, props, "MultiRegionProperties");
+ JsonNode tagList = read(types, props, "Tags");
+ JsonNode policyDocument = read(types, props, "PolicyDocument");
+ types.finish();
+ Boolean deletionProtection = protection == null ? null : protection.booleanValue();
+ String kms = kmsKey == null ? null : kmsKey.asText();
+ String witnessRegion = multiRegion != null && multiRegion.hasNonNull("WitnessRegion")
+ ? multiRegion.get("WitnessRegion").asText() : null;
+ List<String> linkedClusters = multiRegion != null && multiRegion.path("Clusters").isArray()
+ ? strings(multiRegion.get("Clusters")) : null;
+ Map<String, String> tags = tags(tagList);
+ String policy = policyDocument == null ? null : policyDocument.asText();
+
+ DsqlCluster cluster;
+ if (ctx.priorPhysicalId() != null) {
+ String identifier = ctx.priorPhysicalId();
+ dsqlService.updateCluster(region, identifier, deletionProtection, kms, witnessRegion, linkedClusters);
+ reconcileTags(region, dsqlService.getCluster(region, identifier), tags);
+ dsqlService.replaceClusterPolicy(region, identifier, policy);
+ cluster = dsqlService.getCluster(region, identifier);
+ } else {
+ cluster = dsqlService.createCluster(region, deletionProtection, kms, tags, null, witnessRegion,
+ linkedClusters, policy, false);
+ cluster = awaitSettled(region, cluster.getIdentifier());
+ }
+
+ resource.setPhysicalId(cluster.getIdentifier());
+ resource.getAttributes().put("Identifier", cluster.getIdentifier());
+ resource.getAttributes().put("ResourceArn", cluster.getArn());
+ resource.getAttributes().put("CreationTime", CREATION_TIME.format(cluster.getCreationTime()));
+ resource.getAttributes().put("Status", cluster.getStatus());
+ resource.getAttributes().put("Endpoint", cluster.getEndpoint());
+ resource.getAttributes().put("VpcEndpoint", dsqlService.clusterVpcEndpoint(region, cluster.getIdentifier()));
+ resource.getAttributes().put("VpcEndpointServiceName",
+ dsqlService.vpcEndpointServiceName(region, cluster.getIdentifier()));
+ // Measured: PolicyVersion exists only with a policy.
+ if (cluster.getPolicy() != null) {
+ resource.getAttributes().put("PolicyVersion", cluster.getPolicyVersion());
+ } else {
+ resource.getAttributes().remove("PolicyVersion");
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ CfnDeletes.safeDelete("DSQL cluster", physicalId,
+ () -> dsqlService.deleteCluster(region, physicalId), "ResourceNotFoundException");
+ }
+
+ private static JsonNode read(CfnPropertyTypes.Reader types, JsonNode props, String property) {
+ return props == null ? null
+ : types.read(property, props.get(property), CfnPropertyTypes.propertyShape(TYPE, property));
+ }
+
+ private DsqlCluster awaitSettled(String region, String identifier) {
+ Instant deadline = Instant.now().plus(READY_TIMEOUT);
+ while (true) {
+ DsqlCluster cluster = dsqlService.getCluster(region, identifier);
+ if (SETTLED.contains(cluster.getStatus())) {
+ return cluster;
+ }
+ if ("FAILED".equals(cluster.getStatus()) || Instant.now().isAfter(deadline)) {
+ throw new AwsException("InternalFailure", "Cluster " + identifier + " did not become ACTIVE"
+ + " (status " + cluster.getStatus() + ")", 500);
+ }
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("InternalFailure", "Interrupted while cluster " + identifier
+ + " was being created", 500);
+ }
+ }
+ }
+
+ private void reconcileTags(String region, DsqlCluster cluster, Map<String, String> wanted) {
+ List<String> removed = new ArrayList<>();
+ for (String key : cluster.getTags().keySet()) {
+ if (!wanted.containsKey(key)) {
+ removed.add(key);
+ }
+ }
+ if (!removed.isEmpty()) {
+ dsqlService.untagResource(region, cluster.getArn(), removed);
+ }
+ if (!wanted.isEmpty()) {
+ dsqlService.tagResource(region, cluster.getArn(), wanted);
+ }
+ }
+
+ private static Map<String, String> tags(JsonNode tagList) {
+ Map<String, String> tags = new LinkedHashMap<>();
+ if (tagList != null && tagList.isArray()) {
+ for (JsonNode tag : tagList) {
+ tags.put(tag.path("Key").asText(), tag.path("Value").asText(""));
+ }
+ }
+ return tags;
+ }
+
+ private static List<String> strings(JsonNode array) {
+ List<String> values = new ArrayList<>();
+ array.forEach(item -> values.add(item.asText()));
+ return values;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java
new file mode 100644
index 0000000000..6ba78b8760
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java
@@ -0,0 +1,370 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.util.DefaultIndenter;
+import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
+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.services.iam.IamPolicyEvaluator;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+
+/**
+ * A cluster's resource policy as DSQL reads and keeps it (measured, eu-west-1, 2026-10-20).
+ *
+ * <p>DSQL refuses a document with one of three texts: one for JSON it cannot read and for a
+ * statement without a principal or a resource, one for a document missing or misusing an element,
+ * and one for a service principal. It keeps the document in its own form, which GetClusterPolicy
+ * returns: Jackson's default pretty printer, the elements in a fixed order, a list of one value
+ * written as the value, condition values as text, a principal's account id as its root ARN, and
+ * the operators and keys of a condition in the order a {@link HashMap} holds them. A statement
+ * that grants to everyone is refused as public unless a condition restricts it; how DSQL tells is
+ * {@link #restricts}.
+ */
+final class DsqlClusterPolicies {
+
+ static final String UNREADABLE = "Aurora DSQL can't process the request because the policy that you specified"
+ + " isn't valid. Provide the policy in a valid format and try again.";
+ static final String INVALID = "Invalid input for 'policy'. Aurora DSQL can't apply the policy because the policy"
+ + " document isn't valid. Make sure your policy includes all required elements (Version, Statement,"
+ + " Principal, Action, and Resource) in valid JSON format and try again.";
+ static final String SERVICE_PRINCIPAL = "Aurora DSQL can't process the request because the policy contains an"
+ + " invalid service principal. Verify the service principal and try again.";
+ static final String PUBLIC = "Aurora DSQL can't apply the policy because it grants public access. Modify the"
+ + " policy to restrict access and try again.";
+
+ private static final Set<String> DOCUMENT_KEYS = Set.of("Version", "Id", "Statement");
+ private static final Set<String> STATEMENT_KEYS = Set.of(
+ "Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");
+ private static final Set<String> VERSIONS = Set.of("2008-10-17", "2012-10-17");
+ /** Measured: a document without a Version is kept as the older one. */
+ private static final String DEFAULT_VERSION = "2008-10-17";
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ private static final Pattern IAM_ARN = Pattern.compile("arn:[^:]+:iam::\\d{12}:(root|role/.+|user/.+)");
+ /** A role session, which has no record to look up. */
+ private static final Pattern SESSION_ARN = Pattern.compile("arn:[^:]+:sts::\\d{12}:assumed-role/.+");
+ /** Jackson's default pretty printer, with the line feed AWS writes on any platform. */
+ private static final DefaultPrettyPrinter PRETTY =
+ new DefaultPrettyPrinter().withObjectIndenter(new DefaultIndenter(" ", "\n"));
+ private static final String SOURCE_IP = "aws:sourceip";
+ private static final String PRINCIPAL_IS_AWS_SERVICE = "aws:principalisawsservice";
+ /**
+ * The trusted condition keys of DSQL's block public access page, and those it was measured to
+ * accept too: {@code aws:SourceIp}, {@code aws:SourceVpcArn} and the three {@code aws:Vpce*}.
+ * Keys are matched in any case (measured).
+ */
+ private static final Set<String> RESTRICTING_KEYS = lowercase(Set.of(
+ "aws:PrincipalAccount", "aws:PrincipalArn", "aws:PrincipalOrgID", "aws:PrincipalOrgPaths",
+ "aws:SourceAccount", "aws:SourceArn", "aws:SourceVpc", "aws:SourceVpce", "aws:UserId",
+ "aws:PrincipalServiceName", "aws:PrincipalServiceNamesList", "aws:PrincipalIsAWSService",
+ "aws:Ec2InstanceSourceVpc", "aws:SourceOrgID", "aws:SourceOrgPaths",
+ "aws:SourceIp", "aws:SourceVpcArn", "aws:VpceAccount", "aws:VpceOrgID", "aws:VpceOrgPaths"));
+ private static final Set<String> ARN_KEYS = lowercase(Set.of("aws:PrincipalArn", "aws:SourceArn", "aws:SourceVpcArn"));
+
+ private DsqlClusterPolicies() {
+ }
+
+ /**
+ * The policy in the form DSQL keeps it, or the refusal DSQL gives. {@code principalExists}
+ * answers for an IAM principal ARN, which DSQL refuses when it names no one.
+ */
+ static String canonical(ObjectMapper mapper, String policy, String partition, Predicate<String> principalExists) {
+ JsonNode document;
+ try {
+ document = mapper.readTree(policy);
+ } catch (JsonProcessingException e) {
+ throw refused(UNREADABLE);
+ }
+ if (document == null || !document.isObject() || !DOCUMENT_KEYS.containsAll(fieldNames(document))) {
+ throw refused(INVALID);
+ }
+ ObjectNode kept = mapper.createObjectNode();
+ JsonNode version = document.get("Version");
+ if (version != null && !(version.isTextual() && VERSIONS.contains(version.textValue()))) {
+ throw refused(INVALID);
+ }
+ kept.put("Version", version == null ? DEFAULT_VERSION : version.textValue());
+ if (document.has("Id")) {
+ kept.set("Id", text(document.get("Id")));
+ }
+ JsonNode statements = document.get("Statement");
+ List<JsonNode> each = new ArrayList<>();
+ if (statements != null && statements.isObject()) {
+ each.add(statements);
+ } else if (statements != null && statements.isArray()) {
+ statements.forEach(each::add);
+ }
+ if (each.isEmpty()) {
+ throw refused(INVALID);
+ }
+ ArrayNode keptStatements = kept.putArray("Statement");
+ for (JsonNode statement : each) {
+ keptStatements.add(statement(mapper, statement, partition, principalExists));
+ }
+ try {
+ return mapper.writer(PRETTY).writeValueAsString(kept);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("A kept policy is written as JSON", e);
+ }
+ }
+
+ /** Whether DSQL refuses the kept policy as public: an Allow to everyone that no condition restricts. */
+ static boolean grantsPublicAccess(ObjectMapper mapper, String keptPolicy) {
+ try {
+ for (JsonNode statement : mapper.readTree(keptPolicy).path("Statement")) {
+ if ("Allow".equals(statement.path("Effect").asText())
+ && grantsToEveryone(statement.path("Principal"))
+ && !restricts(statement.path("Condition"))) {
+ return true;
+ }
+ }
+ return false;
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("A kept policy is JSON", e);
+ }
+ }
+
+ private static ObjectNode statement(ObjectMapper mapper, JsonNode statement, String partition,
+ Predicate<String> principalExists) {
+ if (!statement.isObject() || !STATEMENT_KEYS.containsAll(fieldNames(statement))) {
+ throw refused(INVALID);
+ }
+ String effect = statement.path("Effect").asText("");
+ if (!effect.equalsIgnoreCase("Allow") && !effect.equalsIgnoreCase("Deny")) {
+ throw refused(INVALID);
+ }
+ if (statement.has("NotPrincipal") || !statement.has("Principal")
+ || statement.has("NotResource") || !statement.has("Resource")) {
+ throw refused(UNREADABLE);
+ }
+ ObjectNode kept = mapper.createObjectNode();
+ if (statement.has("Sid")) {
+ kept.set("Sid", text(statement.get("Sid")));
+ }
+ kept.put("Effect", effect.equalsIgnoreCase("Allow") ? "Allow" : "Deny");
+ kept.set("Principal", principal(mapper, statement.get("Principal"), partition, principalExists));
+ for (String member : List.of("Action", "NotAction", "Resource")) {
+ if (statement.has(member)) {
+ kept.set(member, values(mapper, statement.get(member)));
+ }
+ }
+ if (statement.has("Condition")) {
+ kept.set("Condition", condition(mapper, statement.get("Condition")));
+ }
+ return kept;
+ }
+
+ private static JsonNode principal(ObjectMapper mapper, JsonNode principal, String partition,
+ Predicate<String> principalExists) {
+ if (principal.isTextual()) {
+ if (!"*".equals(principal.textValue())) {
+ throw refused(INVALID);
+ }
+ return principal;
+ }
+ if (!principal.isObject() || principal.isEmpty()) {
+ throw refused(INVALID);
+ }
+ JsonNode service = principal.get("Service");
+ if (service != null) {
+ throw refused(texts(service).contains("*") ? INVALID : SERVICE_PRINCIPAL);
+ }
+ Map<String, JsonNode> kept = new HashMap<>();
+ Iterator<Map.Entry<String, JsonNode>> types = principal.fields();
+ while (types.hasNext()) {
+ Map.Entry<String, JsonNode> type = types.next();
+ switch (type.getKey()) {
+ case "AWS" -> {
+ List<String> arns = new ArrayList<>();
+ for (String value : texts(type.getValue())) {
+ String arn = ACCOUNT_ID.matcher(value).matches()
+ ? "arn:" + partition + ":iam::" + value + ":root" : value;
+ boolean known = "*".equals(arn) || SESSION_ARN.matcher(arn).matches()
+ || IAM_ARN.matcher(arn).matches() && principalExists.test(arn);
+ if (!known) {
+ throw refused(INVALID);
+ }
+ arns.add(arn);
+ }
+ kept.put("AWS", written(mapper, arns));
+ }
+ case "Federated" -> kept.put("Federated", values(mapper, type.getValue()));
+ default -> throw refused(INVALID);
+ }
+ }
+ ObjectNode node = mapper.createObjectNode();
+ kept.forEach(node::set);
+ return node;
+ }
+
+ private static ObjectNode condition(ObjectMapper mapper, JsonNode condition) {
+ if (!condition.isObject()) {
+ throw refused(INVALID);
+ }
+ Map<String, Map<String, JsonNode>> operators = new HashMap<>();
+ Iterator<Map.Entry<String, JsonNode>> each = condition.fields();
+ while (each.hasNext()) {
+ Map.Entry<String, JsonNode> operator = each.next();
+ // Measured: operators are matched as written, so "stringequals" is refused.
+ if (!IamPolicyEvaluator.isSupportedConditionOperator(operator.getKey()) || !operator.getValue().isObject()) {
+ throw refused(INVALID);
+ }
+ Map<String, JsonNode> keys = new HashMap<>();
+ operator.getValue().fields().forEachRemaining(key -> keys.put(key.getKey(), values(mapper, key.getValue())));
+ operators.put(operator.getKey(), keys);
+ }
+ ObjectNode node = mapper.createObjectNode();
+ operators.forEach((operator, keys) -> {
+ ObjectNode keysNode = node.putObject(operator);
+ keys.forEach(keysNode::set);
+ });
+ return node;
+ }
+
+ /**
+ * Whether a condition keeps a statement that grants to everyone from being public, as DSQL
+ * decides (measured): one of the restricting keys, compared with an operator that cannot be met
+ * by just anyone. No value may hold a policy variable, which the caller could fill in. A string
+ * equality restricts whatever else it names, even {@code "*"}, which it takes literally; a string
+ * pattern only a value without a wildcard, and for an ARN key one that pins the account. An ARN
+ * operator's value that is no ARN matches nothing, so it restricts; an ARN must pin the account.
+ * {@code aws:SourceIp} restricts through a narrow range, and {@code aws:PrincipalIsAWSService}
+ * when it is true. {@code ForAnyValue:} reads as the operator it qualifies; {@code ForAllValues:},
+ * {@code IfExists} and the negated operators let a caller without the key through, so they never
+ * restrict.
+ */
+ static boolean restricts(JsonNode condition) {
+ Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
+ while (operators.hasNext()) {
+ Map.Entry<String, JsonNode> operator = operators.next();
+ String name = operator.getKey();
+ if (name.startsWith("ForAnyValue:")) {
+ name = name.substring("ForAnyValue:".length());
+ }
+ Iterator<Map.Entry<String, JsonNode>> keys = operator.getValue().fields();
+ while (keys.hasNext()) {
+ Map.Entry<String, JsonNode> key = keys.next();
+ String lowered = key.getKey().toLowerCase(Locale.ROOT);
+ if (RESTRICTING_KEYS.contains(lowered) && restricts(name, lowered, texts(key.getValue()))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean restricts(String operator, String key, List<String> values) {
+ if (SOURCE_IP.equals(key) && "IpAddress".equals(operator)) {
+ return values.stream().allMatch(DsqlClusterPolicies::isNarrowSourceIp);
+ }
+ return switch (operator) {
+ case "StringEquals", "StringEqualsIgnoreCase" -> values.stream().noneMatch(value -> value.contains("${"));
+ case "StringLike" -> values.stream().allMatch(value -> ARN_KEYS.contains(key)
+ ? pinsAccount(value) && !value.contains("${") : isFixedValue(value));
+ case "ArnEquals", "ArnLike" -> values.stream().allMatch(value -> value.split(":", 6).length < 6
+ || pinsAccount(value) && !value.contains("${"));
+ case "Bool" -> PRINCIPAL_IS_AWS_SERVICE.equals(key) && values.stream().allMatch("true"::equalsIgnoreCase);
+ default -> false;
+ };
+ }
+
+ /** A value that names one thing: not empty, and with no wildcard or policy variable in it. */
+ private static boolean isFixedValue(String value) {
+ return !value.isEmpty() && value.indexOf('*') < 0 && value.indexOf('?') < 0 && !value.contains("${");
+ }
+
+ /** An ARN of six fields whose account has no wildcard. */
+ private static boolean pinsAccount(String arn) {
+ String[] fields = arn.split(":", 6);
+ return fields.length == 6 && fields[4].indexOf('*') < 0 && fields[4].indexOf('?') < 0;
+ }
+
+ /** A range of /8 or narrower for IPv4, /32 for IPv6, or one address (measured /8 restricts, /7 does not). */
+ private static boolean isNarrowSourceIp(String cidr) {
+ int slash = cidr.indexOf('/');
+ if (slash < 0) {
+ return isFixedValue(cidr);
+ }
+ String address = cidr.substring(0, slash);
+ try {
+ int prefixLength = Integer.parseInt(cidr.substring(slash + 1).trim());
+ return isFixedValue(address) && prefixLength >= (address.indexOf(':') >= 0 ? 32 : 8);
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ private static boolean grantsToEveryone(JsonNode principal) {
+ return principal.isTextual() ? "*".equals(principal.textValue()) : texts(principal.path("AWS")).contains("*");
+ }
+
+ /** A value or a list of values, kept as text, the list of one written as its value. */
+ private static JsonNode values(ObjectMapper mapper, JsonNode node) {
+ return written(mapper, texts(node));
+ }
+
+ private static JsonNode written(ObjectMapper mapper, List<String> values) {
+ if (values.size() == 1) {
+ return mapper.getNodeFactory().textNode(values.getFirst());
+ }
+ ArrayNode list = mapper.createArrayNode();
+ values.forEach(list::add);
+ return list;
+ }
+
+ private static List<String> texts(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return values;
+ }
+ if (node.isValueNode()) {
+ values.add(node.asText());
+ return values;
+ }
+ if (!node.isArray() || node.isEmpty()) {
+ throw refused(INVALID);
+ }
+ for (JsonNode item : node) {
+ if (!item.isValueNode() || item.isNull()) {
+ throw refused(INVALID);
+ }
+ values.add(item.asText());
+ }
+ return values;
+ }
+
+ private static JsonNode text(JsonNode node) {
+ if (!node.isTextual()) {
+ throw refused(INVALID);
+ }
+ return node;
+ }
+
+ private static Set<String> fieldNames(JsonNode node) {
+ Set<String> names = new HashSet<>();
+ node.fieldNames().forEachRemaining(names::add);
+ return names;
+ }
+
+ private static Set<String> lowercase(Set<String> keys) {
+ Set<String> lowered = new HashSet<>();
+ keys.forEach(key -> lowered.add(key.toLowerCase(Locale.ROOT)));
+ return Set.copyOf(lowered);
+ }
+
+ private static AwsException refused(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java
new file mode 100644
index 0000000000..a365bfa35b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java
@@ -0,0 +1,292 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+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.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Aurora DSQL's REST-JSON control plane: {@code /cluster}, {@code /cluster/{identifier}} and its
+ * policy, and {@code /clusters/{identifier}/vpc-endpoint-service-name}, as the service model
+ * (2018-05-10) defines them. Tags go through the shared {@code /tags/{resourceArn}} dispatcher.
+ */
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class DsqlController {
+
+ private static final int MAX_POLICY_LENGTH = 20480;
+
+ private final DsqlService service;
+ private final RegionResolver regionResolver;
+
+ @Inject
+ public DsqlController(DsqlService service, RegionResolver regionResolver) {
+ this.service = service;
+ this.regionResolver = regionResolver;
+ }
+
+ @POST
+ @Path("/cluster")
+ public Response createCluster(@Context HttpHeaders headers, Map<String, Object> body) {
+ Map<String, Object> request = body == null ? Map.of() : body;
+ Map<String, Object> multiRegion = map(request.get("multiRegionProperties"));
+ String policy = string(request.get("policy"));
+ if (policy != null) {
+ requirePolicyLength(policy);
+ }
+ DsqlCluster cluster = service.createCluster(regionResolver.resolveRegion(headers),
+ deletionProtection(request.get("deletionProtectionEnabled")), string(request.get("kmsEncryptionKey")),
+ stringMap(request.get("tags")), string(request.get("clientToken")),
+ multiRegion == null ? null : string(multiRegion.get("witnessRegion")),
+ multiRegion == null ? null : strings(multiRegion.get("clusters")), policy,
+ Boolean.TRUE.equals(request.get("bypassPolicyLockoutSafetyCheck")));
+ // Measured: the answer reports the cluster being created, however soon it is ACTIVE, and a
+ // multi-Region one waiting for its peers.
+ Map<String, Object> response = summary(cluster);
+ response.put("status", cluster.getWitnessRegion() != null ? DsqlService.PENDING_SETUP : DsqlService.CREATING);
+ putMultiRegion(response, cluster);
+ response.put("encryptionDetails", encryptionDetails(cluster));
+ response.put("deletionProtectionEnabled", cluster.isDeletionProtectionEnabled());
+ response.put("endpoint", cluster.getEndpoint());
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/cluster")
+ public Response listClusters(@Context HttpHeaders headers, @QueryParam("max-results") Integer maxResults,
+ @QueryParam("next-token") String nextToken) {
+ DsqlService.Page page = service.listClusters(regionResolver.resolveRegion(headers), maxResults, nextToken);
+ List<Map<String, Object>> clusters = new ArrayList<>();
+ for (DsqlCluster cluster : page.clusters()) {
+ Map<String, Object> entry = new LinkedHashMap<>();
+ entry.put("identifier", cluster.getIdentifier());
+ entry.put("arn", cluster.getArn());
+ clusters.add(entry);
+ }
+ Map<String, Object> response = new LinkedHashMap<>();
+ if (page.nextToken() != null) {
+ response.put("nextToken", page.nextToken());
+ }
+ response.put("clusters", clusters);
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/cluster/{identifier}")
+ public Response getCluster(@Context HttpHeaders headers, @PathParam("identifier") String identifier) {
+ DsqlCluster cluster = service.getCluster(regionResolver.resolveRegion(headers), identifier);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("identifier", cluster.getIdentifier());
+ response.put("arn", cluster.getArn());
+ response.put("status", cluster.getStatus());
+ response.put("creationTime", epochSeconds(cluster));
+ response.put("deletionProtectionEnabled", cluster.isDeletionProtectionEnabled());
+ putMultiRegion(response, cluster);
+ if (!cluster.getTags().isEmpty()) {
+ response.put("tags", cluster.getTags());
+ }
+ response.put("encryptionDetails", encryptionDetails(cluster));
+ response.put("endpoint", cluster.getEndpoint());
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/cluster/{identifier}")
+ public Response updateCluster(@Context HttpHeaders headers, @PathParam("identifier") String identifier,
+ Map<String, Object> body) {
+ Map<String, Object> request = body == null ? Map.of() : body;
+ Map<String, Object> multiRegion = map(request.get("multiRegionProperties"));
+ DsqlCluster cluster = service.updateCluster(regionResolver.resolveRegion(headers), identifier,
+ deletionProtection(request.get("deletionProtectionEnabled")), string(request.get("kmsEncryptionKey")),
+ multiRegion == null ? null : string(multiRegion.get("witnessRegion")),
+ multiRegion == null ? null : strings(multiRegion.get("clusters")));
+ // Measured: the answer reports the update in progress; the cluster is ACTIVE right after.
+ Map<String, Object> response = summary(cluster);
+ response.put("status", DsqlService.UPDATING);
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/cluster/{identifier}")
+ public Response deleteCluster(@Context HttpHeaders headers, @PathParam("identifier") String identifier,
+ @QueryParam("client-token") String clientToken) {
+ DsqlCluster cluster = service.deleteCluster(regionResolver.resolveRegion(headers), identifier);
+ Map<String, Object> response = summary(cluster);
+ // Measured: a multi-Region cluster's deletion first waits on its peers.
+ response.put("status", cluster.getWitnessRegion() != null ? DsqlService.PENDING_DELETE : DsqlService.DELETING);
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/clusters/{identifier}/vpc-endpoint-service-name")
+ public Response getVpcEndpointServiceName(@Context HttpHeaders headers,
+ @PathParam("identifier") String identifier) {
+ String region = regionResolver.resolveRegion(headers);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("serviceName", service.vpcEndpointServiceName(region, identifier));
+ response.put("clusterVpcEndpoint", service.clusterVpcEndpoint(region, identifier));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/cluster/{identifier}/policy")
+ public Response putClusterPolicy(@Context HttpHeaders headers, @PathParam("identifier") String identifier,
+ Map<String, Object> body) {
+ Map<String, Object> request = body == null ? Map.of() : body;
+ String policy = string(request.get("policy"));
+ if (policy == null) {
+ throw policyConstraint("Member must not be null");
+ }
+ requirePolicyLength(policy);
+ String version = service.putClusterPolicy(regionResolver.resolveRegion(headers), identifier, policy,
+ string(request.get("expectedPolicyVersion")),
+ Boolean.TRUE.equals(request.get("bypassPolicyLockoutSafetyCheck")));
+ return Response.ok(Map.of("policyVersion", version)).build();
+ }
+
+ @GET
+ @Path("/cluster/{identifier}/policy")
+ public Response getClusterPolicy(@Context HttpHeaders headers, @PathParam("identifier") String identifier) {
+ DsqlCluster cluster = service.getClusterPolicy(regionResolver.resolveRegion(headers), identifier);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("policy", cluster.getPolicy());
+ response.put("policyVersion", cluster.getPolicyVersion());
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/cluster/{identifier}/policy")
+ public Response deleteClusterPolicy(@Context HttpHeaders headers, @PathParam("identifier") String identifier,
+ @QueryParam("expected-policy-version") String expectedPolicyVersion,
+ @QueryParam("client-token") String clientToken) {
+ String version = service.deleteClusterPolicy(regionResolver.resolveRegion(headers), identifier,
+ expectedPolicyVersion);
+ return Response.ok(Map.of("policyVersion", version)).build();
+ }
+
+ // ── Shapes ────────────────────────────────────────────────────────────────
+
+ private static Map<String, Object> summary(DsqlCluster cluster) {
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("identifier", cluster.getIdentifier());
+ response.put("arn", cluster.getArn());
+ response.put("status", cluster.getStatus());
+ response.put("creationTime", epochSeconds(cluster));
+ return response;
+ }
+
+ private static void putMultiRegion(Map<String, Object> response, DsqlCluster cluster) {
+ if (cluster.getWitnessRegion() == null && cluster.getLinkedClusterArns() == null) {
+ return;
+ }
+ Map<String, Object> multiRegion = new LinkedHashMap<>();
+ if (cluster.getWitnessRegion() != null) {
+ multiRegion.put("witnessRegion", cluster.getWitnessRegion());
+ }
+ if (cluster.getLinkedClusterArns() != null) {
+ multiRegion.put("clusters", cluster.getLinkedClusterArns());
+ }
+ response.put("multiRegionProperties", multiRegion);
+ }
+
+ static Map<String, Object> encryptionDetails(DsqlCluster cluster) {
+ Map<String, Object> details = new LinkedHashMap<>();
+ if (cluster.getKmsEncryptionKey() != null) {
+ details.put("encryptionType", "CUSTOMER_MANAGED_KMS_KEY");
+ details.put("kmsKeyArn", cluster.getKmsEncryptionKey());
+ } else {
+ details.put("encryptionType", "AWS_OWNED_KMS_KEY");
+ }
+ details.put("encryptionStatus", "ENABLED");
+ return details;
+ }
+
+ private static double epochSeconds(DsqlCluster cluster) {
+ return cluster.getCreationTime().toEpochMilli() / 1000.0;
+ }
+
+ private static String string(Object value) {
+ return value instanceof String text ? text : null;
+ }
+
+ /**
+ * deletionProtectionEnabled as DSQL reads it (measured, eu-west-1, 2026-10-20): a boolean, or
+ * text that is false when it spells false in any case and true otherwise ("yes", "TRUE", "1");
+ * null leaves it out. Empty text, a number, an object and a list fail to deserialize.
+ */
+ private static Boolean deletionProtection(Object value) {
+ if (value == null || value instanceof Boolean) {
+ return (Boolean) value;
+ }
+ if (value instanceof String text) {
+ if (text.isEmpty()) {
+ throw serialization("Unexpected token received from parser");
+ }
+ return !"false".equalsIgnoreCase(text);
+ }
+ if (value instanceof Number) {
+ throw serialization("NUMBER_VALUE cannot be converted to Boolean");
+ }
+ throw serialization(value instanceof Map<?, ?> ? "Start of structure or map found where not expected" : "");
+ }
+
+ /** The model's bounds on a policy, refused with the texts measured on DSQL. */
+ private static void requirePolicyLength(String policy) {
+ if (policy.isEmpty()) {
+ throw policyConstraint("Member must have length greater than or equal to 1");
+ }
+ if (policy.length() > MAX_POLICY_LENGTH) {
+ throw policyConstraint("Member must have length less than or equal to " + MAX_POLICY_LENGTH);
+ }
+ }
+
+ private static AwsException policyConstraint(String constraint) {
+ return new AwsException("ValidationException", "1 validation error detected: Value at 'policy' failed to"
+ + " satisfy constraint: " + constraint, 400);
+ }
+
+ private static AwsException serialization(String message) {
+ return new AwsException("SerializationException", message, 400);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<String, Object> map(Object value) {
+ return value instanceof Map<?, ?> map ? (Map<String, Object>) map : null;
+ }
+
+ private static Map<String, String> stringMap(Object value) {
+ if (!(value instanceof Map<?, ?> map)) {
+ return null;
+ }
+ Map<String, String> result = new LinkedHashMap<>();
+ map.forEach((key, entry) -> result.put(String.valueOf(key), entry == null ? "" : String.valueOf(entry)));
+ return result;
+ }
+
+ private static List<String> strings(Object value) {
+ if (!(value instanceof List<?> list)) {
+ return null;
+ }
+ List<String> result = new ArrayList<>();
+ list.forEach(item -> result.add(String.valueOf(item)));
+ return result;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlane.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlane.java
new file mode 100644
index 0000000000..a0ad87a860
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlane.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.util.function.Consumer;
+
+/**
+ * The databases behind the clusters. A cluster has none here: it is ready as soon as it is
+ * created, and its endpoint is named but not served.
+ */
+@ApplicationScoped
+public class DsqlDataPlane {
+
+ /** Starts the cluster's database, then reports whether it is ready to serve. */
+ public void provision(DsqlCluster cluster, Consumer<Boolean> onReady) {
+ onReady.accept(true);
+ }
+
+ /** Stops the cluster's database and drops its data, then runs {@code onGone}. */
+ public void deprovision(DsqlCluster cluster, Runnable onGone) {
+ onGone.run();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlIdentifiers.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlIdentifiers.java
new file mode 100644
index 0000000000..7cb003f770
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlIdentifiers.java
@@ -0,0 +1,76 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import java.nio.ByteBuffer;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/**
+ * Aurora DSQL's identifiers: a UUID written as 26 characters of lowercase RFC 4648 base32 without
+ * padding, the shape of cluster ids, job ids and session ids (measured: the UUID
+ * {@code 00000000-0000-0000-0000-000000000001} is {@code aaaaaaaaaaaaaaaaaaaaaaaaae}). The 128 bits
+ * leave two zero bits in the last character, so a string of the right alphabet and length can still
+ * name no UUID, which DSQL refuses with its own message.
+ */
+public final class DsqlIdentifiers {
+
+ /** The constraint DSQL's model puts on a cluster id, and the message it gives for one that fails it. */
+ public static final Pattern CLUSTER_ID = Pattern.compile("[a-z0-9]{26}");
+
+ private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
+
+ private DsqlIdentifiers() {
+ }
+
+ public static String newId() {
+ return encode(UUID.randomUUID());
+ }
+
+ public static String encode(UUID uuid) {
+ ByteBuffer bytes = ByteBuffer.allocate(16);
+ bytes.putLong(uuid.getMostSignificantBits());
+ bytes.putLong(uuid.getLeastSignificantBits());
+ StringBuilder out = new StringBuilder(26);
+ int buffer = 0;
+ int bits = 0;
+ for (byte b : bytes.array()) {
+ buffer = (buffer << 8) | (b & 0xff);
+ bits += 8;
+ while (bits >= 5) {
+ out.append(ALPHABET.charAt((buffer >> (bits - 5)) & 31));
+ bits -= 5;
+ }
+ }
+ out.append(ALPHABET.charAt((buffer << (5 - bits)) & 31));
+ return out.toString();
+ }
+
+ /** The UUID {@code id} names, or empty when it is not 26 base32 characters naming one. */
+ public static Optional<UUID> decode(String id) {
+ if (id == null || id.length() != 26) {
+ return Optional.empty();
+ }
+ long high = 0;
+ long low = 0;
+ int bitIndex = 0;
+ for (char c : id.toLowerCase(Locale.ROOT).toCharArray()) {
+ int value = ALPHABET.indexOf(c);
+ if (value < 0) {
+ return Optional.empty();
+ }
+ for (int i = 4; i >= 0; i--) {
+ long bit = (value >> i) & 1;
+ if (bitIndex < 64) {
+ high |= bit << (63 - bitIndex);
+ } else if (bitIndex < 128) {
+ low |= bit << (127 - bitIndex);
+ } else if (bit != 0) {
+ return Optional.empty();
+ }
+ bitIndex++;
+ }
+ }
+ return Optional.of(new UUID(high, low));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
new file mode 100644
index 0000000000..71d83399f5
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
@@ -0,0 +1,64 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.context.ContextNotActiveException;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+
+/**
+ * Who is calling, and whether an IAM principal a cluster policy names exists: what DSQL checks a
+ * policy against. A credential that names no IAM identity is its account's root, as for STS.
+ */
+@ApplicationScoped
+public class DsqlPrincipals {
+
+ private final IamService iamService;
+ private final RegionResolver regionResolver;
+ private final Instance<RequestContext> requestContext;
+
+ @Inject
+ public DsqlPrincipals(IamService iamService, RegionResolver regionResolver,
+ Instance<RequestContext> requestContext) {
+ this.iamService = iamService;
+ this.regionResolver = regionResolver;
+ this.requestContext = requestContext;
+ }
+
+ public CallerArns caller() {
+ String accountId = regionResolver.getAccountId();
+ return iamService.resolveCallerArns(accessKeyId())
+ .orElseGet(() -> CallerArns.accountRoot(regionResolver.buildGlobalArn("iam", accountId, "root"),
+ accountId));
+ }
+
+ /**
+ * Whether the IAM principal {@code arn} names exists. Floci takes every account to exist, so an
+ * account's root always does; a role or a user is looked up in its account by its name.
+ */
+ public boolean exists(String arn) {
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ String resource = parsed.resource();
+ String name = resource.substring(resource.lastIndexOf('/') + 1);
+ if (resource.startsWith("role/")) {
+ return iamService.findRole(parsed.accountId(), name).isPresent();
+ }
+ if (resource.startsWith("user/")) {
+ return iamService.findUser(parsed.accountId(), name).isPresent();
+ }
+ return "root".equals(resource);
+ }
+
+ private String accessKeyId() {
+ try {
+ return requestContext.isResolvable() ? requestContext.get().getAccessKeyId() : null;
+ } catch (ContextNotActiveException e) {
+ // A call outside a request, such as CloudFormation's, is the account's own.
+ return null;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java
new file mode 100644
index 0000000000..be14e610ce
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java
@@ -0,0 +1,625 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
+import io.github.hectorvent.floci.services.iam.RequestPrincipal;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Aurora DSQL's control plane: clusters, their tags and resource policies. Each cluster's
+ * database is run by {@link DsqlDataPlane}, which reports when it is ready; until then a cluster
+ * is {@code CREATING}, as on AWS. A multi-Region cluster waits in {@code PENDING_SETUP} until it
+ * and each of its peers name one another. Errors carry the messages measured on AWS (eu-west-1,
+ * 2026-10-16 and 2026-10-20).
+ */
+@ApplicationScoped
+public class DsqlService implements Resettable {
+
+ private static final Logger LOG = Logger.getLogger(DsqlService.class);
+
+ static final String CREATING = "CREATING";
+ static final String ACTIVE = "ACTIVE";
+ static final String UPDATING = "UPDATING";
+ static final String DELETING = "DELETING";
+ static final String FAILED = "FAILED";
+ static final String PENDING_SETUP = "PENDING_SETUP";
+ static final String PENDING_DELETE = "PENDING_DELETE";
+
+ private static final int MAX_RESULTS = 100;
+ private static final String PUT_POLICY = "dsql:PutClusterPolicy";
+ private static final String DELETE_POLICY = "dsql:DeleteClusterPolicy";
+ private static final String INVALID_PAGE_TOKEN = "Invalid pagination token. Request a new token and try again.";
+ static final String LOCKOUT = "The new policy would result in the calling principal being unable to further"
+ + " update and delete this cluster's policy. Set the 'bypassPolicyLockoutSafetyCheck' parameter to"
+ + " 'true' to confirm this intent.";
+
+ private final AccountAwareStorageBackend<DsqlCluster> clusters;
+ private final RegionResolver regionResolver;
+ private final String endpointSuffix;
+ private final DsqlDataPlane dataPlane;
+ private final DsqlPrincipals principals;
+ private final IamPolicyEvaluator policyEvaluator;
+ private final ObjectMapper objectMapper;
+ private final Map<String, Object> locks = new ConcurrentHashMap<>();
+
+ @Inject
+ public DsqlService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
+ DsqlDataPlane dataPlane, DsqlPrincipals principals, IamPolicyEvaluator policyEvaluator,
+ ObjectMapper objectMapper) {
+ this(storageFactory.create("dsql", "dsql-clusters.json", new TypeReference<>() {}), regionResolver,
+ config.services().dsql().endpointSuffix(), dataPlane, principals, policyEvaluator, objectMapper);
+ }
+
+ DsqlService(AccountAwareStorageBackend<DsqlCluster> clusters, RegionResolver regionResolver,
+ String endpointSuffix, DsqlDataPlane dataPlane, DsqlPrincipals principals,
+ IamPolicyEvaluator policyEvaluator, ObjectMapper objectMapper) {
+ this.clusters = clusters;
+ this.regionResolver = regionResolver;
+ this.endpointSuffix = endpointSuffix;
+ this.dataPlane = dataPlane;
+ this.principals = principals;
+ this.policyEvaluator = policyEvaluator;
+ this.objectMapper = objectMapper;
+ }
+
+ // ── Clusters ──────────────────────────────────────────────────────────────
+
+ public DsqlCluster createCluster(String region, Boolean deletionProtectionEnabled, String kmsEncryptionKey,
+ Map<String, String> tags, String clientToken, String witnessRegion,
+ List<String> linkedClusterArns, String policy,
+ boolean bypassPolicyLockoutSafetyCheck) {
+ String accountId = regionResolver.getAccountId();
+ synchronized (lockFor(accountId + "::" + region)) {
+ String request = clientRequest(deletionProtectionEnabled, kmsEncryptionKey, tags, witnessRegion,
+ linkedClusterArns, policy);
+ if (clientToken != null) {
+ Optional<DsqlCluster> earlier = clusters.scan(key -> key.startsWith(region + "::")).stream()
+ .filter(cluster -> clientToken.equals(cluster.getClientToken()))
+ .findFirst();
+ if (earlier.isPresent()) {
+ // Measured: the same token with other parameters is a conflict, not the earlier cluster.
+ if (!request.equals(earlier.get().getClientRequest())) {
+ throw new AwsException("ConflictException",
+ "Requests using a client token should supply identical request parameters", 409);
+ }
+ return earlier.get();
+ }
+ }
+ String identifier = DsqlIdentifiers.newId();
+ String arn = clusterArn(region, identifier);
+ String keptPolicy = policy == null ? null
+ : checkedPolicy(policy, arn, region, bypassPolicyLockoutSafetyCheck);
+ DsqlCluster cluster = new DsqlCluster();
+ cluster.setIdentifier(identifier);
+ cluster.setArn(arn);
+ cluster.setAccountId(accountId);
+ cluster.setRegion(region);
+ cluster.setCreationTime(Instant.now());
+ // Measured: a cluster created without the member has deletion protection.
+ cluster.setDeletionProtectionEnabled(deletionProtectionEnabled == null || deletionProtectionEnabled);
+ cluster.setKmsEncryptionKey(customerKey(kmsEncryptionKey));
+ cluster.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
+ cluster.setEndpoint(endpointFor(identifier, region));
+ cluster.setClientToken(clientToken);
+ cluster.setClientRequest(clientToken == null ? null : request);
+ cluster.setWitnessRegion(blankToNull(witnessRegion));
+ cluster.setLinkedClusterArns(linkedClusters(arn, cluster.getWitnessRegion(), linkedClusterArns));
+ // Measured: a multi-Region cluster waits for its peers, a single-Region one is being created.
+ cluster.setStatus(cluster.getWitnessRegion() != null ? PENDING_SETUP : CREATING);
+ if (keptPolicy != null) {
+ cluster.setPolicy(keptPolicy);
+ // Measured: a policy's version is when it was set, in epoch milliseconds.
+ cluster.setPolicyVersion(String.valueOf(cluster.getCreationTime().toEpochMilli()));
+ }
+ clusters.put(key(region, identifier), cluster);
+ LOG.infov("Created DSQL cluster {0} in {1}", identifier, region);
+ dataPlane.provision(cluster, ready -> markReady(accountId, region, identifier, ready));
+ return cluster;
+ }
+ }
+
+ public DsqlCluster getCluster(String region, String identifier) {
+ requireIdentifier(identifier);
+ return clusters.get(key(region, identifier))
+ .orElseThrow(() -> notFound(clusterArn(region, identifier), identifier));
+ }
+
+ public Page listClusters(String region, Integer maxResults, String nextToken) {
+ if (maxResults != null && (maxResults < 1 || maxResults > MAX_RESULTS)) {
+ // Measured: unlike other model checks, this one does not quote the value.
+ throw new AwsException("ValidationException", "1 validation error detected: Value at 'maxResults'"
+ + " failed to satisfy constraint: Member must have value "
+ + (maxResults < 1 ? "greater than or equal to 1" : "less than or equal to 100"), 400);
+ }
+ List<DsqlCluster> all = new ArrayList<>(clusters.scan(key -> key.startsWith(region + "::")));
+ all.sort(Comparator.comparing(DsqlCluster::getCreationTime).thenComparing(DsqlCluster::getIdentifier));
+ int start = 0;
+ if (nextToken != null && !nextToken.isBlank()) {
+ // The token holds the sort position of the next page's first cluster, so a page carries
+ // on from there even when that cluster is gone, as on AWS (measured).
+ String[] position = tokenPosition(nextToken);
+ start = all.size();
+ for (int i = 0; i < all.size(); i++) {
+ DsqlCluster cluster = all.get(i);
+ int order = cluster.getCreationTime().compareTo(Instant.parse(position[0]));
+ if (order > 0 || (order == 0 && cluster.getIdentifier().compareTo(position[1]) >= 0)) {
+ start = i;
+ break;
+ }
+ }
+ }
+ int size = maxResults == null ? MAX_RESULTS : maxResults;
+ int end = Math.min(all.size(), start + size);
+ String next = end < all.size() ? pageToken(all.get(end)) : null;
+ return new Page(all.subList(start, end), next);
+ }
+
+ /** A member left null keeps its value. */
+ public DsqlCluster updateCluster(String region, String identifier, Boolean deletionProtectionEnabled,
+ String kmsEncryptionKey, String witnessRegion, List<String> linkedClusterArns) {
+ DsqlCluster cluster = getCluster(region, identifier);
+ synchronized (lockFor(cluster.getArn())) {
+ if (deletionProtectionEnabled != null) {
+ cluster.setDeletionProtectionEnabled(deletionProtectionEnabled);
+ }
+ if (kmsEncryptionKey != null) {
+ cluster.setKmsEncryptionKey(customerKey(kmsEncryptionKey));
+ }
+ if (witnessRegion != null) {
+ cluster.setWitnessRegion(blankToNull(witnessRegion));
+ }
+ if (linkedClusterArns != null) {
+ cluster.setLinkedClusterArns(linkedClusters(cluster.getArn(), cluster.getWitnessRegion(),
+ linkedClusterArns));
+ }
+ clusters.put(key(region, identifier), cluster);
+ }
+ completePeering(cluster);
+ return cluster;
+ }
+
+ public DsqlCluster deleteCluster(String region, String identifier) {
+ DsqlCluster cluster = getCluster(region, identifier);
+ String accountId = regionResolver.getAccountId();
+ synchronized (lockFor(cluster.getArn())) {
+ if (cluster.isDeletionProtectionEnabled()) {
+ throw new AwsException("ValidationException", "Can't delete cluster: Deletion protection is enabled."
+ + " To proceed, disable deletion protection and try again.", 400,
+ Map.of("reason", "deletionProtectionEnabled"));
+ }
+ if (DELETING.equals(cluster.getStatus())) {
+ return cluster;
+ }
+ cluster.setStatus(DELETING);
+ clusters.put(key(region, identifier), cluster);
+ }
+ dataPlane.deprovision(cluster, () -> {
+ clusters.deleteForAccount(accountId, key(region, identifier));
+ locks.remove(cluster.getArn());
+ LOG.infov("Deleted DSQL cluster {0} in {1}", identifier, region);
+ });
+ return cluster;
+ }
+
+ /** The cluster whose endpoint is {@code host}, in any account: what the data plane serves. */
+ public Optional<DsqlCluster> clusterForEndpoint(String host) {
+ if (host == null) {
+ return Optional.empty();
+ }
+ String wanted = host.toLowerCase(Locale.ROOT);
+ return clusters.scanAllAccounts().stream()
+ .filter(cluster -> wanted.equals(cluster.getEndpoint()))
+ .findFirst();
+ }
+
+ /** Every cluster in every account, for the data plane to bring back after a restart. */
+ public List<DsqlCluster> allClusters() {
+ return clusters.scanAllAccounts();
+ }
+
+ // ── VPC endpoint service ──────────────────────────────────────────────────
+
+ public String vpcEndpointServiceName(String region, String identifier) {
+ getCluster(region, identifier);
+ return "com.amazonaws." + region + ".dsql-" + regionalServiceSuffix(region);
+ }
+
+ public String clusterVpcEndpoint(String region, String identifier) {
+ return identifier + ".dsql-" + regionalServiceSuffix(region) + "." + region + "." + endpointSuffix;
+ }
+
+ // ── Resource policy ───────────────────────────────────────────────────────
+
+ public String putClusterPolicy(String region, String identifier, String policy, String expectedPolicyVersion,
+ boolean bypassPolicyLockoutSafetyCheck) {
+ requireIdentifier(identifier);
+ String arn = clusterArn(region, identifier);
+ String keptPolicy = checkedPolicy(policy, arn, region, bypassPolicyLockoutSafetyCheck);
+ DsqlCluster cluster = getCluster(region, identifier);
+ synchronized (lockFor(cluster.getArn())) {
+ // Measured: with no policy any expected version is not found; with one, another version conflicts.
+ if (expectedPolicyVersion != null && cluster.getPolicy() == null) {
+ throw policyVersionNotFound(identifier, expectedPolicyVersion);
+ }
+ if (expectedPolicyVersion != null && !expectedPolicyVersion.equals(cluster.getPolicyVersion())) {
+ throw new AwsException("ConflictException", policyVersionMessage(identifier, expectedPolicyVersion),
+ 409, Map.of("resourceId", identifier, "resourceType", "cluster"));
+ }
+ cluster.setPolicy(keptPolicy);
+ cluster.setPolicyVersion(nextPolicyVersion(cluster));
+ clusters.put(key(region, identifier), cluster);
+ return cluster.getPolicyVersion();
+ }
+ }
+
+ public DsqlCluster getClusterPolicy(String region, String identifier) {
+ DsqlCluster cluster = getCluster(region, identifier);
+ if (cluster.getPolicy() == null) {
+ throw policyNotFound(identifier);
+ }
+ return cluster;
+ }
+
+ /** Answers the version of the policy deleted, as DSQL does (measured). */
+ public String deleteClusterPolicy(String region, String identifier, String expectedPolicyVersion) {
+ DsqlCluster cluster = getCluster(region, identifier);
+ synchronized (lockFor(cluster.getArn())) {
+ if (cluster.getPolicy() == null) {
+ throw policyNotFound(identifier);
+ }
+ if (expectedPolicyVersion != null && !expectedPolicyVersion.equals(cluster.getPolicyVersion())) {
+ throw policyVersionNotFound(identifier, expectedPolicyVersion);
+ }
+ String version = cluster.getPolicyVersion();
+ cluster.setPolicy(null);
+ cluster.setPolicyVersion(null);
+ clusters.put(key(region, identifier), cluster);
+ return version;
+ }
+ }
+
+ /**
+ * Gives the cluster {@code policy}, or none when it is null, as CloudFormation's update does
+ * (measured): a policy the cluster already keeps is left as it is, version included.
+ */
+ public void replaceClusterPolicy(String region, String identifier, String policy) {
+ DsqlCluster cluster = getCluster(region, identifier);
+ if (policy == null) {
+ if (cluster.getPolicy() != null) {
+ deleteClusterPolicy(region, identifier, null);
+ }
+ return;
+ }
+ if (!checkedPolicy(policy, cluster.getArn(), region, false).equals(cluster.getPolicy())) {
+ putClusterPolicy(region, identifier, policy, null, false);
+ }
+ }
+
+ /** The policy as DSQL keeps it in its own form, once it has passed every check DSQL makes. */
+ String checkedPolicy(String policy, String clusterArn, String region, boolean bypassPolicyLockoutSafetyCheck) {
+ String kept = DsqlClusterPolicies.canonical(objectMapper, policy, regionResolver.getPartition(),
+ principals::exists);
+ if (DsqlClusterPolicies.grantsPublicAccess(objectMapper, kept)) {
+ throw new AwsException("ValidationException", DsqlClusterPolicies.PUBLIC, 400);
+ }
+ if (!bypassPolicyLockoutSafetyCheck && deniesCaller(kept, clusterArn, region, PUT_POLICY)
+ && deniesCaller(kept, clusterArn, region, DELETE_POLICY)) {
+ // Measured: refused only when the caller could neither replace nor delete the policy.
+ throw new AwsException("ValidationException", LOCKOUT, 400);
+ }
+ return kept;
+ }
+
+ private boolean deniesCaller(String policy, String clusterArn, String region, String action) {
+ CallerArns caller = principals.caller();
+ Map<String, List<String>> context = new HashMap<>();
+ caller.putPrincipalKeys(context);
+ String accountId = regionResolver.getAccountId();
+ Map<String, List<String>> effective = IamConditionContextResolver.withGlobalContext(
+ context, clusterArn, region, accountId, accountId);
+ return policyEvaluator.evaluateResourcePolicyFor(List.of(policy), RequestPrincipal.caller(caller),
+ action, clusterArn, effective) == ResourcePolicyDecision.EXPLICIT_DENY;
+ }
+
+ // ── Tags ──────────────────────────────────────────────────────────────────
+
+ public Map<String, String> listTags(String region, String arn) {
+ DsqlCluster cluster = clusterForArn(region, arn, "ListTagsForResource");
+ synchronized (lockFor(cluster.getArn())) {
+ return new LinkedHashMap<>(cluster.getTags());
+ }
+ }
+
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ DsqlCluster cluster = clusterForArn(region, arn, "TagResource");
+ synchronized (lockFor(cluster.getArn())) {
+ cluster.getTags().putAll(tags == null ? Map.of() : tags);
+ clusters.put(key(cluster.getRegion(), cluster.getIdentifier()), cluster);
+ }
+ }
+
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ DsqlCluster cluster = clusterForArn(region, arn, "UntagResource");
+ synchronized (lockFor(cluster.getArn())) {
+ (tagKeys == null ? List.<String>of() : tagKeys).forEach(cluster.getTags()::remove);
+ clusters.put(key(cluster.getRegion(), cluster.getIdentifier()), cluster);
+ }
+ }
+
+ @Override
+ public void clear() {
+ for (DsqlCluster cluster : clusters.scanAllAccounts()) {
+ dataPlane.deprovision(cluster, () -> { });
+ }
+ clusters.clear();
+ locks.clear();
+ }
+
+ // ── Internals ─────────────────────────────────────────────────────────────
+
+ private void markReady(String accountId, String region, String identifier, boolean ready) {
+ clusters.getForAccount(accountId, key(region, identifier)).ifPresent(cluster -> {
+ if (CREATING.equals(cluster.getStatus())) {
+ cluster.setStatus(ready ? ACTIVE : FAILED);
+ clusters.putForAccount(accountId, key(region, identifier), cluster);
+ }
+ });
+ }
+
+ /**
+ * A multi-Region cluster's clusters as DSQL lists them (measured): its peers as given, then
+ * itself. A single-Region cluster has none.
+ */
+ private static List<String> linkedClusters(String arn, String witnessRegion, List<String> peers) {
+ List<String> linked = new ArrayList<>();
+ if (peers != null) {
+ peers.stream().filter(peer -> !peer.equals(arn) && !linked.contains(peer)).forEach(linked::add);
+ }
+ if (witnessRegion == null && linked.isEmpty()) {
+ return null;
+ }
+ linked.add(arn);
+ return List.copyOf(linked);
+ }
+
+ /**
+ * Brings out of {@code PENDING_SETUP} every cluster of {@code cluster}'s group once each names
+ * every other, as DSQL does when the last peer is updated (measured: both ACTIVE after about
+ * 100 s; here at once).
+ */
+ private void completePeering(DsqlCluster cluster) {
+ if (cluster.getLinkedClusterArns() == null) {
+ return;
+ }
+ List<DsqlCluster> group = new ArrayList<>();
+ for (String arn : cluster.getLinkedClusterArns()) {
+ Optional<DsqlCluster> member = clusterOfArn(arn);
+ if (member.isEmpty()) {
+ return;
+ }
+ group.add(member.get());
+ }
+ Set<String> names = new HashSet<>(cluster.getLinkedClusterArns());
+ if (group.size() < 2 || group.stream().anyMatch(member -> member.getWitnessRegion() == null
+ || !names.equals(new HashSet<>(member.getLinkedClusterArns())))) {
+ return;
+ }
+ for (DsqlCluster member : group) {
+ synchronized (lockFor(member.getArn())) {
+ if (PENDING_SETUP.equals(member.getStatus())) {
+ member.setStatus(ACTIVE);
+ clusters.put(key(member.getRegion(), member.getIdentifier()), member);
+ }
+ }
+ }
+ }
+
+ private Optional<DsqlCluster> clusterOfArn(String arn) {
+ AwsArnUtils.Arn parsed = clusterArnOrNull(arn);
+ if (parsed == null || !regionResolver.getAccountId().equals(parsed.accountId())) {
+ return Optional.empty();
+ }
+ return clusters.get(key(parsed.region(), parsed.resource().substring("cluster/".length())));
+ }
+
+ /**
+ * The cluster a tag call names, refused as DSQL refuses it (measured): an ARN that is not a
+ * well-formed cluster ARN as access denied, another account's as not authorized, another
+ * Region's as a bad request, and one of no cluster as not found.
+ */
+ private DsqlCluster clusterForArn(String region, String arn, String action) {
+ AwsArnUtils.Arn parsed = clusterArnOrNull(arn);
+ String caller = principals.caller().callerArn();
+ if (parsed == null) {
+ throw new AwsException("AccessDeniedException", "Invalid input for 'resourceArn'. The cluster ARN that you"
+ + " specified isn't valid. Provide the cluster ARN in the format"
+ + " 'arn:partition:dsql:region:account-id:cluster/cluster-id' and try again.User: " + caller
+ + " is not authorized to perform: dsql:" + action + " on resource: * with an explicit deny in a"
+ + " resource-based policy", 403);
+ }
+ if (!regionResolver.getAccountId().equals(parsed.accountId())) {
+ // Measured: another account's cluster is refused, not looked up in the caller's.
+ throw new AwsException("AccessDeniedException", "User: " + caller + " is not authorized to perform: dsql:"
+ + action + " on resource: " + arn + " because no resource-based policy allows the dsql:" + action
+ + " action", 403);
+ }
+ if (!region.equals(parsed.region())) {
+ throw new AwsException("BadRequestException", "Invalid input resource arn: expected region " + region, 400);
+ }
+ return clusters.get(key(region, parsed.resource().substring("cluster/".length())))
+ .orElseThrow(() -> new AwsException("NotFoundException", "Resource was not found", 404));
+ }
+
+ /** {@code arn} parsed when it is a cluster ARN with a cluster id DSQL accepts, else null. */
+ private static AwsArnUtils.Arn clusterArnOrNull(String arn) {
+ AwsArnUtils.Arn parsed;
+ try {
+ parsed = AwsArnUtils.parse(arn);
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ String resource = parsed.resource();
+ if (!"dsql".equals(parsed.service()) || !resource.startsWith("cluster/")) {
+ return null;
+ }
+ String identifier = resource.substring("cluster/".length());
+ return DsqlIdentifiers.CLUSTER_ID.matcher(identifier).matches()
+ && DsqlIdentifiers.decode(identifier).isPresent() ? parsed : null;
+ }
+
+ private String endpointFor(String identifier, String region) {
+ return identifier + ".dsql." + region + "." + endpointSuffix;
+ }
+
+ private String clusterArn(String region, String identifier) {
+ return regionResolver.buildArn("dsql", region, "cluster/" + identifier);
+ }
+
+ /**
+ * The four characters after {@code dsql-} in a Region's VPC endpoint service name, the same
+ * for every cluster of the Region (eu-west-1 is {@code 2syq} on AWS). Floci derives them from
+ * the Region's name, so they are stable.
+ */
+ private static String regionalServiceSuffix(String region) {
+ byte[] digest = Digests.sha256(region.getBytes(StandardCharsets.UTF_8));
+ String alphabet = "abcdefghijklmnopqrstuvwxyz234567";
+ StringBuilder suffix = new StringBuilder(4);
+ for (int i = 0; i < 4; i++) {
+ suffix.append(alphabet.charAt(digest[i] & 31));
+ }
+ return suffix.toString();
+ }
+
+ /**
+ * A cluster id must match DSQL's pattern, and then name a UUID: both refusals carry the texts
+ * measured on AWS.
+ */
+ static void requireIdentifier(String identifier) {
+ if (identifier == null || !DsqlIdentifiers.CLUSTER_ID.matcher(identifier).matches()) {
+ throw new AwsException("ValidationException", "1 validation error detected: Value at 'identifier'"
+ + " failed to satisfy constraint: Member must satisfy regular expression pattern: [a-z0-9]{26}", 400);
+ }
+ if (DsqlIdentifiers.decode(identifier).isEmpty()) {
+ throw new AwsException("ValidationException", "Invalid input 'identifier: " + identifier
+ + "'. The cluster identifier format is invalid. Provide a valid cluster identifier and try again.",
+ 400);
+ }
+ }
+
+ private static AwsException notFound(String arn, String identifier) {
+ return new AwsException("ResourceNotFoundException", "The resource with ARN " + arn
+ + " doesn't exist. Verify the ARN and try again.", 404,
+ Map.of("resourceId", identifier, "resourceType", "cluster"));
+ }
+
+ private static AwsException policyNotFound(String identifier) {
+ return new AwsException("ResourceNotFoundException", "Aurora DSQL can't find the policy for the resource "
+ + identifier + ". Verify that the policy exists.", 404,
+ Map.of("resourceId", identifier, "resourceType", "policy"));
+ }
+
+ private static AwsException policyVersionNotFound(String identifier, String version) {
+ return new AwsException("ResourceNotFoundException", policyVersionMessage(identifier, version), 404,
+ Map.of("resourceId", identifier, "resourceType", "policy"));
+ }
+
+ private static String policyVersionMessage(String identifier, String version) {
+ return "Aurora DSQL can't find policy version " + version + " for resource " + identifier
+ + ". Verify that the policy exists and that the version is correct.";
+ }
+
+ /** When the policy is set, in epoch milliseconds, after the version it replaces. */
+ private static String nextPolicyVersion(DsqlCluster cluster) {
+ long now = Instant.now().toEpochMilli();
+ try {
+ return String.valueOf(cluster.getPolicyVersion() == null ? now
+ : Math.max(now, Long.parseLong(cluster.getPolicyVersion()) + 1));
+ } catch (NumberFormatException e) {
+ return String.valueOf(now);
+ }
+ }
+
+ private Object lockFor(String key) {
+ return locks.computeIfAbsent(key, k -> new Object());
+ }
+
+ private static String key(String region, String identifier) {
+ return region + "::" + identifier;
+ }
+
+ private static String blankToNull(String value) {
+ return value == null || value.isBlank() ? null : value;
+ }
+
+ /** A customer-managed key, or null for AWS's own: blank, or the reserved AWS_OWNED_KMS_KEY (measured). */
+ private static String customerKey(String kmsEncryptionKey) {
+ return "AWS_OWNED_KMS_KEY".equals(kmsEncryptionKey) ? null : blankToNull(kmsEncryptionKey);
+ }
+
+ /** What a create asked for, which a later create with the same client token must repeat. */
+ private static String clientRequest(Boolean deletionProtectionEnabled, String kmsEncryptionKey,
+ Map<String, String> tags, String witnessRegion,
+ List<String> linkedClusterArns, String policy) {
+ return String.join("\n", String.valueOf(deletionProtectionEnabled), String.valueOf(kmsEncryptionKey),
+ String.valueOf(tags == null ? null : new TreeMap<>(tags)), String.valueOf(witnessRegion),
+ String.valueOf(linkedClusterArns), String.valueOf(policy));
+ }
+
+ private static String pageToken(DsqlCluster cluster) {
+ String position = cluster.getCreationTime() + " " + cluster.getIdentifier();
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(position.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static String[] tokenPosition(String nextToken) {
+ try {
+ String[] position = new String(Base64.getUrlDecoder().decode(nextToken), StandardCharsets.UTF_8)
+ .split(" ", 2);
+ if (position.length == 2) {
+ Instant.parse(position[0]);
+ return position;
+ }
+ } catch (IllegalArgumentException | DateTimeParseException invalid) {
+ // Refused below.
+ }
+ // Measured: the one refusal here that says which member and why.
+ throw new AwsException("ValidationException", INVALID_PAGE_TOKEN, 400, Map.of(
+ "reason", "fieldValidationFailed",
+ "fieldList", List.of(Map.of("name", "next-token", "message", INVALID_PAGE_TOKEN))));
+ }
+
+ /** One page of ListClusters. */
+ public record Page(List<DsqlCluster> clusters, String nextToken) {
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlTagHandler.java
new file mode 100644
index 0000000000..420e33248e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlTagHandler.java
@@ -0,0 +1,50 @@
+package io.github.hectorvent.floci.services.dsql;
+
+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;
+
+/** Aurora DSQL's {@code /tags/{resourceArn}}: a {@code tags} map, POST to tag, answered 200. */
+@ApplicationScoped
+public class DsqlTagHandler implements TagHandler {
+
+ private final DsqlService service;
+
+ @Inject
+ public DsqlTagHandler(DsqlService service) {
+ this.service = service;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "dsql";
+ }
+
+ @Override
+ public int tagResourceSuccessStatus() {
+ return 200;
+ }
+
+ @Override
+ public int untagResourceSuccessStatus() {
+ return 200;
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return service.listTags(region, arn);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ service.tagResource(region, arn, tags);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ service.untagResource(region, arn, tagKeys);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/model/DsqlCluster.java b/src/main/java/io/github/hectorvent/floci/services/dsql/model/DsqlCluster.java
new file mode 100644
index 0000000000..5b18d55816
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/model/DsqlCluster.java
@@ -0,0 +1,69 @@
+package io.github.hectorvent.floci.services.dsql.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** An Aurora DSQL cluster as Floci stores it. The wire shapes are built from it by the controller. */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DsqlCluster {
+
+ private String identifier;
+ private String arn;
+ private String accountId;
+ private String region;
+ private String status;
+ private Instant creationTime;
+ private boolean deletionProtectionEnabled;
+ private Map<String, String> tags = new LinkedHashMap<>();
+ private String kmsEncryptionKey;
+ private String endpoint;
+ private String clientToken;
+ private String clientRequest;
+ private String policy;
+ private String policyVersion;
+ private String witnessRegion;
+ private List<String> linkedClusterArns;
+
+ public String getIdentifier() { return identifier; }
+ public void setIdentifier(String identifier) { this.identifier = identifier; }
+ public String getArn() { return arn; }
+ public void setArn(String arn) { this.arn = arn; }
+ public String getAccountId() { return accountId; }
+ public void setAccountId(String accountId) { this.accountId = accountId; }
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public Instant getCreationTime() { return creationTime; }
+ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
+ public boolean isDeletionProtectionEnabled() { return deletionProtectionEnabled; }
+ public void setDeletionProtectionEnabled(boolean deletionProtectionEnabled) {
+ this.deletionProtectionEnabled = deletionProtectionEnabled;
+ }
+ public Map<String, String> getTags() { return tags; }
+ public void setTags(Map<String, String> tags) { this.tags = tags == null ? new LinkedHashMap<>() : tags; }
+ public String getKmsEncryptionKey() { return kmsEncryptionKey; }
+ public void setKmsEncryptionKey(String kmsEncryptionKey) { this.kmsEncryptionKey = kmsEncryptionKey; }
+ public String getEndpoint() { return endpoint; }
+ public void setEndpoint(String endpoint) { this.endpoint = endpoint; }
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+ public String getClientRequest() { return clientRequest; }
+ public void setClientRequest(String clientRequest) { this.clientRequest = clientRequest; }
+ public String getPolicy() { return policy; }
+ public void setPolicy(String policy) { this.policy = policy; }
+ public String getPolicyVersion() { return policyVersion; }
+ public void setPolicyVersion(String policyVersion) { this.policyVersion = policyVersion; }
+ public String getWitnessRegion() { return witnessRegion; }
+ public void setWitnessRegion(String witnessRegion) { this.witnessRegion = witnessRegion; }
+ public List<String> getLinkedClusterArns() { return linkedClusterArns; }
+ public void setLinkedClusterArns(List<String> linkedClusterArns) { this.linkedClusterArns = linkedClusterArns; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 7abe15142b..294b306c1e 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -538,6 +538,9 @@ floci:
enabled: true
transaction-ttl-seconds: 180
database-resuming-exception-enabled: false # FLOCI_SERVICES_RDS_DATA_DATABASE_RESUMING_EXCEPTION_ENABLED
+ dsql:
+ enabled: true
+ endpoint-suffix: localhost.floci.io # FLOCI_SERVICES_DSQL_ENDPOINT_SUFFIX; endpoints are <id>.dsql.<region>.<suffix>
redshift-data:
enabled: true
result-ttl-hours: 24
diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json
index 5a808a96d7..b1b544d724 100644
--- a/src/main/resources/aws/cfn-property-types.json
+++ b/src/main/resources/aws/cfn-property-types.json
@@ -7,6 +7,7 @@
},
"operations": {
"AWS::AutoScaling::LaunchConfiguration": "AWS::AutoScaling::LaunchConfiguration",
+ "AWS::DSQL::Cluster": "AWS::DSQL::Cluster",
"AWS::EC2::Instance": "AWS::EC2::Instance",
"AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate",
"AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition",
@@ -87,6 +88,59 @@
"HttpEndpoint": "String"
}
},
+ "AWS::DSQL::Cluster": {
+ "type": "structure",
+ "members": {
+ "DeletionProtectionEnabled": "Boolean",
+ "Tags": "AWS::DSQL::Cluster.Tags",
+ "ResourceArn": "String",
+ "Identifier": "String",
+ "CreationTime": "String",
+ "Status": "String",
+ "VpcEndpointServiceName": "String",
+ "MultiRegionProperties": "AWS::DSQL::Cluster.MultiRegionProperties",
+ "KmsEncryptionKey": "String",
+ "EncryptionDetails": "AWS::DSQL::Cluster.EncryptionDetails",
+ "Endpoint": "String",
+ "VpcEndpoint": "String",
+ "PolicyVersion": "String",
+ "PolicyDocument": "String"
+ }
+ },
+ "AWS::DSQL::Cluster.EncryptionDetails": {
+ "type": "structure",
+ "members": {
+ "EncryptionStatus": "String",
+ "EncryptionType": "String",
+ "KmsKeyArn": "String"
+ }
+ },
+ "AWS::DSQL::Cluster.MultiRegionProperties": {
+ "type": "structure",
+ "members": {
+ "WitnessRegion": "String",
+ "Clusters": "AWS::DSQL::Cluster.MultiRegionProperties.Clusters"
+ }
+ },
+ "AWS::DSQL::Cluster.MultiRegionProperties.Clusters": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::DSQL::Cluster.Tags": {
+ "type": "list",
+ "member": "AWS::DSQL::Cluster/Tag"
+ },
+ "AWS::DSQL::Cluster/Tag": {
+ "type": "structure",
+ "members": {
+ "Key": "String",
+ "Value": "String"
+ },
+ "required": [
+ "Key",
+ "Value"
+ ]
+ },
"AWS::EC2::Instance": {
"type": "structure",
"members": {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java
index 4e196e79cd..03f817e922 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java
@@ -41,7 +41,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
"accessanalyzer", "acm", "amazonmq", "apigateway", "apigatewayv2", "applicationautoscaling", "appsync",
"aps", "autoscaling", "backup", "batch", "bcmdataexports", "bedrock", "bedrockagentcorecontrol", "ce",
"cloudfront", "cloudmap", "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito",
- "configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dynamodb", "ec2",
+ "configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dsql", "dynamodb", "ec2",
"ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elbv2", "emr", "emrserverless",
"eventbridge", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
@@ -516,6 +516,19 @@ class PartitionCrossServiceSmokeIntegrationTest {
assertRegionalHostIn(partitionCase, URI.create(issuer).getHost());
}
+ @ParameterizedTest
+ @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
+ void dsqlClusterArn(PartitionCase partitionCase) {
+ String region = offered(partitionCase, "dsql");
+ Response created = signed(region, "dsql")
+ .contentType(JSON)
+ .body("{\"deletionProtectionEnabled\":false}")
+ .when().post("/cluster").then().statusCode(200).extract().response();
+ String identifier = created.jsonPath().getString("identifier");
+ cleanup.register(() -> signed(region, "dsql").when().delete("/cluster/" + identifier));
+ PartitionMatrix.assertArnIn(partitionCase, created.jsonPath().getString("arn"));
+ }
+
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void cognitoUserPoolArn(PartitionCase partitionCase) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 342970e2f5..2c4fb8d5db 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -48,6 +48,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUs
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserToGroupAttachmentCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CustomResourceCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.DsqlCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2InstanceCfnProvisioner;
@@ -120,6 +121,7 @@ import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsS
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.configservice.AwsConfigService;
import io.github.hectorvent.floci.services.docdb.DocDbService;
+import io.github.hectorvent.floci.services.dsql.DsqlService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend;
@@ -248,6 +250,7 @@ final class CfnProvisionerFixture {
private AwsConfigService awsConfigService;
private OrganizationsService organizationsService;
private SqsService sqsService;
+ private DsqlService dsqlService;
private WafV2Service wafV2Service;
private BackupService backupService;
private ElastiCacheService elastiCacheService;
@@ -441,6 +444,9 @@ final class CfnProvisionerFixture {
if (organizationsService != null) {
discovered.add(new OrganizationsCfnProvisioner(organizationsService));
}
+ if (dsqlService != null) {
+ discovered.add(new DsqlCfnProvisioner(dsqlService));
+ }
if (sqsService != null) {
discovered.add(new SqsCfnProvisioner(sqsService));
}
@@ -774,6 +780,11 @@ final class CfnProvisionerFixture {
return this;
}
+ public Builder dsql(DsqlService v) {
+ this.dsqlService = v;
+ return this;
+ }
+
public Builder sqs(SqsService v) {
this.sqsService = v;
return this;
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDsqlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDsqlIntegrationTest.java
new file mode 100644
index 0000000000..7599c3fd5d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDsqlIntegrationTest.java
@@ -0,0 +1,192 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.matchesPattern;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * {@code AWS::DSQL::Cluster}, measured on CloudFormation (eu-west-1, 2026-10-16 and 2026-10-20):
+ * Ref is the identifier, the read-only properties are attributes, a cluster created without
+ * DeletionProtectionEnabled is protected, and deleting the stack then fails.
+ */
+@QuarkusTest
+class CloudFormationDsqlIntegrationTest {
+
+ private static final String TEMPLATE = """
+ {"Resources": {"Cluster": {"Type": "AWS::DSQL::Cluster", "Properties": %s}},
+ "Outputs": {
+ "Ref": {"Value": {"Ref": "Cluster"}},
+ "Identifier": {"Value": {"Fn::GetAtt": ["Cluster", "Identifier"]}},
+ "ResourceArn": {"Value": {"Fn::GetAtt": ["Cluster", "ResourceArn"]}},
+ "Status": {"Value": {"Fn::GetAtt": ["Cluster", "Status"]}},
+ "Endpoint": {"Value": {"Fn::GetAtt": ["Cluster", "Endpoint"]}},
+ "VpcEndpoint": {"Value": {"Fn::GetAtt": ["Cluster", "VpcEndpoint"]}},
+ "VpcEndpointServiceName": {"Value": {"Fn::GetAtt": ["Cluster", "VpcEndpointServiceName"]}},
+ "CreationTime": {"Value": {"Fn::GetAtt": ["Cluster", "CreationTime"]}}}}
+ """;
+
+ @Test
+ void aClusterGetsItsReferenceAndAttributes() {
+ createStack("dsql-cluster", TEMPLATE.formatted("""
+ {"DeletionProtectionEnabled": false, "Tags": [{"Key": "team", "Value": "data"}]}"""));
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal("dsql-cluster").status());
+
+ Map<String, String> outputs = outputs("dsql-cluster");
+ String identifier = outputs.get("Ref");
+ assertThat(identifier, matchesPattern("[a-z2-7]{26}"));
+ assertEquals(identifier, outputs.get("Identifier"));
+ assertEquals("arn:aws:dsql:us-east-1:000000000000:cluster/" + identifier, outputs.get("ResourceArn"));
+ assertEquals("ACTIVE", outputs.get("Status"));
+ assertEquals(identifier + ".dsql.us-east-1.localhost.floci.io", outputs.get("Endpoint"));
+ assertThat(outputs.get("VpcEndpoint"), matchesPattern(identifier + "\\.dsql-[a-z2-7]{4}\\.us-east-1\\..+"));
+ assertThat(outputs.get("VpcEndpointServiceName"), matchesPattern("com\\.amazonaws\\.us-east-1\\.dsql-[a-z2-7]{4}"));
+ assertThat(outputs.get("CreationTime"), matchesPattern("\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z"));
+
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack").formParam("StackName", "dsql-cluster")
+ .when().post("/").then().statusCode(200);
+ CfnStackWaits.awaitStackDeleted("dsql-cluster");
+ }
+
+ @Test
+ void aProtectedClusterKeepsItsStackFromBeingDeleted() {
+ createStack("dsql-protected", TEMPLATE.formatted("{}"));
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal("dsql-protected").status());
+
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack").formParam("StackName", "dsql-protected")
+ .when().post("/").then().statusCode(200);
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal("dsql-protected");
+ assertEquals("DELETE_FAILED", state.status());
+ assertThat(state.reason(), containsString("failed to delete"));
+ }
+
+ /** AWS::NoValue leaves a property out: the cluster is protected by default and has no policy. */
+ @Test
+ void aPropertyLeftOutByNoValueTakesItsDefault() {
+ createStack("dsql-novalue", """
+ {"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
+ "Resources": {"Cluster": {"Type": "AWS::DSQL::Cluster", "Properties": {
+ "DeletionProtectionEnabled": {"Fn::If": ["Never", false, {"Ref": "AWS::NoValue"}]},
+ "PolicyDocument": {"Fn::If": ["Never", "{}", {"Ref": "AWS::NoValue"}]}}}},
+ "Outputs": {"Ref": {"Value": {"Ref": "Cluster"}}}}""");
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal("dsql-novalue").status());
+ String identifier = outputs("dsql-novalue").get("Ref");
+ String auth = "AWS4-HMAC-SHA256 Credential=test/20261016/us-east-1/dsql/aws4_request, SignedHeaders=host, Signature=abc";
+
+ given().header("Authorization", auth).get("/cluster/" + identifier).then().statusCode(200)
+ .body("deletionProtectionEnabled", equalTo(true));
+ given().header("Authorization", auth).get("/cluster/" + identifier + "/policy").then().statusCode(404);
+
+ given().header("Authorization", auth).contentType("application/json").body(Map.of("deletionProtectionEnabled", false))
+ .post("/cluster/" + identifier).then().statusCode(200);
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack").formParam("StackName", "dsql-novalue")
+ .when().post("/").then().statusCode(200);
+ CfnStackWaits.awaitStackDeleted("dsql-novalue");
+ }
+
+ /**
+ * Measured (eu-west-1, 2026-10-20, stack floci-measure-dsql-update): the tags follow the
+ * template, a policy left as it was keeps its version and a changed one gets a new one, and a
+ * template that sets nothing removes the tags and the policy but leaves deletion protection as
+ * it was rather than back at its default.
+ */
+ @Test
+ void anUpdateLeavesWhatTheTemplateNoLongerSetsButTheTagsAndThePolicy() {
+ String stack = "dsql-update";
+ createStack(stack, updatable("""
+ {"DeletionProtectionEnabled": "FALSE", "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}],
+ "PolicyDocument": %s}""".formatted(policy("One")), true));
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
+ String identifier = outputs(stack).get("Ref");
+ String first = outputs(stack).get("PolicyVersion");
+
+ updateStack(stack, updatable("""
+ {"DeletionProtectionEnabled": false, "Tags": [{"Key": "a", "Value": "3"}], "PolicyDocument": %s}"""
+ .formatted(policy("One")), true));
+ assertEquals(first, outputs(stack).get("PolicyVersion"));
+ dsql().get("/cluster/" + identifier).then().statusCode(200).body("tags", equalTo(Map.of("a", "3")));
+
+ updateStack(stack, updatable("""
+ {"DeletionProtectionEnabled": false, "Tags": [{"Key": "a", "Value": "3"}], "PolicyDocument": %s}"""
+ .formatted(policy("Two")), true));
+ assertThat(Long.parseLong(outputs(stack).get("PolicyVersion")), greaterThan(Long.parseLong(first)));
+
+ updateStack(stack, updatable("{}", false));
+ dsql().get("/cluster/" + identifier).then().statusCode(200)
+ .body("deletionProtectionEnabled", equalTo(false))
+ .body("tags", nullValue());
+ dsql().get("/cluster/" + identifier + "/policy").then().statusCode(404);
+
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack").formParam("StackName", stack)
+ .when().post("/").then().statusCode(200);
+ CfnStackWaits.awaitStackDeleted(stack);
+ }
+
+ /** Measured: the schema's types are checked before the cluster is created. */
+ @Test
+ void aPolicyDocumentThatIsNoTextFailsTheResource() {
+ createStack("dsql-object-policy", TEMPLATE.formatted("""
+ {"DeletionProtectionEnabled": false, "PolicyDocument": {"Version": "2012-10-17"}}"""));
+
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal("dsql-object-policy");
+ assertEquals("ROLLBACK_COMPLETE", state.status());
+ assertThat(CfnStackWaits.failedResourceReason("dsql-object-policy"),
+ containsString("Property [PolicyDocument] expected type: String, found: JSONObject"));
+ }
+
+ private static String updatable(String properties, boolean policyVersion) {
+ return """
+ {"Resources": {"Cluster": {"Type": "AWS::DSQL::Cluster", "Properties": %s}},
+ "Outputs": {"Ref": {"Value": {"Ref": "Cluster"}}%s}}"""
+ .formatted(properties, policyVersion
+ ? ", \"PolicyVersion\": {\"Value\": {\"Fn::GetAtt\": [\"Cluster\", \"PolicyVersion\"]}}" : "");
+ }
+
+ /** A Deny of connections from outside one VPC, as text, the type the schema gives PolicyDocument. */
+ private static String policy(String sid) {
+ String document = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"" + sid + "\",\"Effect\":\"Deny\","
+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\",\"Condition\":"
+ + "{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}}]}";
+ return "\"" + document.replace("\"", "\\\"") + "\"";
+ }
+
+ private static void updateStack(String name, String template) {
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack").formParam("StackName", name).formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+ assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
+ }
+
+ private static RequestSpecification dsql() {
+ return given().header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20261016/us-east-1/dsql/aws4_request, SignedHeaders=host, Signature=abc");
+ }
+
+ private static void createStack(String name, String template) {
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack").formParam("StackName", name).formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+ }
+
+ private static Map<String, String> outputs(String name) {
+ String xml = given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks").formParam("StackName", name)
+ .when().post("/").then().statusCode(200).extract().asString();
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisionerTest.java
new file mode 100644
index 0000000000..36d60ebb4c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DsqlCfnProvisionerTest.java
@@ -0,0 +1,161 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.dsql.DsqlService;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code AWS::DSQL::Cluster} against a mocked {@link DsqlService}, with what CloudFormation was
+ * measured to do (eu-west-1, 2026-10-20): properties read against the resource schema, a create
+ * that settles on PENDING_SETUP for a multi-Region cluster, and an update that leaves a property it
+ * no longer sets as it was, but for the tags and the policy.
+ */
+class DsqlCfnProvisionerTest {
+
+ private static final String REGION = "eu-west-1";
+ private static final String ID = "aaaaaaaaaaaaaaaaaaaaaaaaaa";
+ private static final String ARN = "arn:aws:dsql:eu-west-1:111122223333:cluster/" + ID;
+ private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
+
+ private final DsqlService dsql = mock(DsqlService.class);
+ private final DsqlCfnProvisioner provisioner = new DsqlCfnProvisioner(dsql);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void aCreateReadsTextAsTheSchemaTypesItAndSettlesOnPendingSetup() throws Exception {
+ DsqlCluster cluster = cluster("PENDING_SETUP", Map.of());
+ cluster.setPolicy(POLICY);
+ cluster.setPolicyVersion("1792496211976");
+ when(dsql.createCluster(any(), any(), any(), any(), any(), any(), any(), any(), anyBoolean())).thenReturn(cluster);
+ when(dsql.getCluster(REGION, ID)).thenReturn(cluster);
+ StackResource resource = resource();
+
+ provisioner.provision(resource, props("""
+ {"DeletionProtectionEnabled": "FALSE", "Tags": [{"Key": "team", "Value": "data"}],
+ "MultiRegionProperties": {"WitnessRegion": "eu-west-2"}, "PolicyDocument": %s}
+ """.formatted(mapper.writeValueAsString(POLICY))), context(null));
+
+ verify(dsql).createCluster(REGION, false, null, Map.of("team", "data"), null, "eu-west-2", null, POLICY, false);
+ assertEquals(ID, resource.getPhysicalId());
+ assertEquals("PENDING_SETUP", resource.getAttributes().get("Status"));
+ assertEquals("1792496211976", resource.getAttributes().get("PolicyVersion"));
+ assertEquals(ARN, resource.getAttributes().get("ResourceArn"));
+ }
+
+ @Test
+ void anUpdateLeavesWhatTheTemplateNoLongerSetsButTheTagsAndThePolicy() throws Exception {
+ DsqlCluster cluster = cluster("ACTIVE", Map.of("team", "data", "env", "test"));
+ when(dsql.getCluster(REGION, ID)).thenReturn(cluster);
+ StackResource resource = resource();
+ resource.getAttributes().put("PolicyVersion", "1792496211976");
+
+ provisioner.provision(resource, props("{\"Tags\": [{\"Key\": \"team\", \"Value\": \"platform\"}]}"),
+ context(ID));
+
+ verify(dsql).updateCluster(REGION, ID, null, null, null, null);
+ verify(dsql).untagResource(REGION, ARN, List.of("env"));
+ verify(dsql).tagResource(REGION, ARN, Map.of("team", "platform"));
+ verify(dsql).replaceClusterPolicy(REGION, ID, null);
+ verify(dsql, never()).createCluster(any(), any(), any(), any(), any(), any(), any(), any(), anyBoolean());
+ assertFalse(resource.getAttributes().containsKey("PolicyVersion"));
+ }
+
+ @Test
+ void anUpdateHandsOverTheValuesTheTemplateSets() throws Exception {
+ when(dsql.getCluster(REGION, ID)).thenReturn(cluster("ACTIVE", Map.of()));
+
+ provisioner.provision(resource(), props("""
+ {"DeletionProtectionEnabled": true, "KmsEncryptionKey": "AWS_OWNED_KMS_KEY",
+ "MultiRegionProperties": {"WitnessRegion": "eu-west-2", "Clusters": ["arn:aws:dsql:eu-west-3:111122223333:cluster/b"]},
+ "PolicyDocument": %s}
+ """.formatted(mapper.writeValueAsString(POLICY))), context(ID));
+
+ verify(dsql).updateCluster(REGION, ID, true, "AWS_OWNED_KMS_KEY", "eu-west-2",
+ List.of("arn:aws:dsql:eu-west-3:111122223333:cluster/b"));
+ verify(dsql).replaceClusterPolicy(REGION, ID, POLICY);
+ }
+
+ @Test
+ void noValueLeavesAPropertyOut() throws Exception {
+ when(dsql.getCluster(REGION, ID)).thenReturn(cluster("ACTIVE", Map.of()));
+
+ provisioner.provision(resource(), props("{\"DeletionProtectionEnabled\": {\"Ref\": \"AWS::NoValue\"}}"),
+ context(ID));
+
+ verify(dsql).updateCluster(eq(REGION), eq(ID), isNull(), isNull(), isNull(), isNull());
+ }
+
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', value = {
+ "{\"PolicyDocument\": {\"Version\": \"2012-10-17\"}} | Property [PolicyDocument] expected type: String, found: JSONObject",
+ "{\"Tags\": \"x\"} | Property [Tags] expected type: JSONArray, found: String",
+ "{\"MultiRegionProperties\": \"x\"} | Property [MultiRegionProperties] expected type: JSONObject, found: String",
+ "{\"DeletionProtectionEnabled\": \"yes\"} | Model validation failed (#/DeletionProtectionEnabled: expected type: Boolean, found: String)"
+ })
+ void aValueOfAnotherTypeFailsTheResourceBeforeAnythingIsCreated(String properties, String message) {
+ AwsException failed = assertThrows(AwsException.class,
+ () -> provisioner.provision(resource(), props(properties), context(null)));
+
+ assertEquals(message, failed.getMessage());
+ verify(dsql, never()).createCluster(any(), any(), any(), any(), any(), any(), any(), any(), anyBoolean());
+ }
+
+ private ProvisionContext context(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone("111122223333", REGION, "stack",
+ mapper, UnaryOperator.identity());
+ return new ProvisionContext(engine, REGION, "111122223333", "stack", priorPhysicalId);
+ }
+
+ private JsonNode props(String json) {
+ try {
+ return mapper.readTree(json);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static StackResource resource() {
+ StackResource resource = new StackResource();
+ resource.setLogicalId("Cluster");
+ resource.setResourceType("AWS::DSQL::Cluster");
+ resource.setAttributes(new HashMap<>());
+ return resource;
+ }
+
+ private static DsqlCluster cluster(String status, Map<String, String> tags) {
+ DsqlCluster cluster = new DsqlCluster();
+ cluster.setIdentifier(ID);
+ cluster.setArn(ARN);
+ cluster.setStatus(status);
+ cluster.setCreationTime(Instant.parse("2026-10-20T11:27:22.382Z"));
+ cluster.setEndpoint(ID + ".dsql.eu-west-1.localhost.floci.io");
+ cluster.setTags(new LinkedHashMap<>(tags));
+ return cluster;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPoliciesTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPoliciesTest.java
new file mode 100644
index 0000000000..c9ca8f4075
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPoliciesTest.java
@@ -0,0 +1,269 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Cluster policies as DSQL reads and keeps them. Every expected text is what GetClusterPolicy
+ * answered on AWS for the same document, and every refusal and public verdict was measured
+ * (eu-west-1, 2026-10-20).
+ */
+class DsqlClusterPoliciesTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String ACCOUNT = "111122223333";
+ private static final String DENY_OUTSIDE_VPC = "\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"*\"},"
+ + "\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\","
+ + "\"Condition\":{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}";
+
+ @Test
+ void aPolicyIsKeptInDsqlsForm() {
+ assertEquals("""
+ {
+ "Version" : "2012-10-17",
+ "Statement" : [ {
+ "Sid" : "One",
+ "Effect" : "Deny",
+ "Principal" : {
+ "AWS" : "*"
+ },
+ "Action" : "dsql:DbConnect",
+ "Resource" : "*",
+ "Condition" : {
+ "StringNotEquals" : {
+ "aws:SourceVpc" : "vpc-0123456789abcdef0"
+ }
+ }
+ } ]
+ }""", kept("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"One\",\"Effect\":\"Deny\","
+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"dsql:DbConnect\"],\"Resource\":\"*\",\"Condition\":"
+ + "{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}}]}"));
+ }
+
+ @Test
+ void aStatementObjectBecomesAListAndItsMembersTakeTheirOrder() {
+ assertEquals("""
+ {
+ "Version" : "2012-10-17",
+ "Statement" : [ {
+ "Sid" : "Two",
+ "Effect" : "Deny",
+ "Principal" : "*",
+ "Action" : [ "dsql:DbConnect", "dsql:DbConnectAdmin" ],
+ "Resource" : "*",
+ "Condition" : {
+ "StringNotEquals" : {
+ "aws:SourceVpc" : "vpc-0123456789abcdef0"
+ }
+ }
+ } ]
+ }""", kept("{\"Statement\":{\"Effect\":\"Deny\",\"Sid\":\"Two\",\"Principal\":\"*\","
+ + "\"Action\":[\"dsql:DbConnect\",\"dsql:DbConnectAdmin\"],\"Resource\":[\"*\"],\"Condition\":"
+ + "{\"StringNotEquals\":{\"aws:SourceVpc\":[\"vpc-0123456789abcdef0\"]}}},\"Version\":\"2012-10-17\"}"));
+ }
+
+ @Test
+ void conditionsAreKeptAsTextInTheOrderAHashMapHoldsThem() {
+ assertEquals("""
+ {
+ "Version" : "2012-10-17",
+ "Statement" : [ {
+ "Sid" : "B",
+ "Effect" : "Deny",
+ "Principal" : "*",
+ "Action" : "dsql:DbConnect",
+ "Resource" : "*",
+ "Condition" : {
+ "Bool" : {
+ "aws:SecureTransport" : "false"
+ },
+ "StringNotEquals" : {
+ "aws:PrincipalAccount" : "111122223333",
+ "aws:SourceVpc" : [ "vpc-0123456789abcdef0", "vpc-0123456789abcdef1" ]
+ },
+ "NumericLessThan" : {
+ "aws:MultiFactorAuthAge" : "3600"
+ }
+ }
+ } ]
+ }""", kept("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"B\",\"Effect\":\"Deny\","
+ + "\"Principal\":\"*\",\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\",\"Condition\":{"
+ + "\"StringNotEquals\":{\"aws:SourceVpc\":[\"vpc-0123456789abcdef0\",\"vpc-0123456789abcdef1\"],"
+ + "\"aws:PrincipalAccount\":\"111122223333\"},\"Bool\":{\"aws:SecureTransport\":false},"
+ + "\"NumericLessThan\":{\"aws:MultiFactorAuthAge\":3600}}}]}"));
+ }
+
+ @Test
+ void anAccountIdBecomesItsRootAndAMissingVersionTheOlderOne() {
+ String kept = kept("{\"Statement\":[{\"Effect\":\"deny\",\"Principal\":{\"AWS\":[\"" + ACCOUNT + "\"]},"
+ + "\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}]}");
+
+ assertEquals("{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":"
+ + "\"arn:aws:iam::" + ACCOUNT + ":root\"},\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}]}",
+ compact(kept));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("refusals")
+ void aDocumentIsRefusedAsDsqlRefusesIt(String measured, String policy, String message) {
+ AwsException refused = assertThrows(AwsException.class, () -> kept(policy));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertEquals(message, refused.getMessage());
+ }
+
+ static Stream<Arguments> refusals() {
+ String unreadable = DsqlClusterPolicies.UNREADABLE;
+ String invalid = DsqlClusterPolicies.INVALID;
+ return Stream.of(
+ Arguments.of("not JSON", "not json", unreadable),
+ Arguments.of("a JSON array", "[]", invalid),
+ Arguments.of("no Statement", "{\"Version\":\"2012-10-17\"}", invalid),
+ Arguments.of("an empty Statement", "{\"Version\":\"2012-10-17\",\"Statement\":[]}", invalid),
+ Arguments.of("a Version of no year", document("{" + DENY_OUTSIDE_VPC + "}", "2099-01-01"), invalid),
+ Arguments.of("a member of no document", "{\"Version\":\"2012-10-17\",\"Foo\":\"x\",\"Statement\":[{"
+ + DENY_OUTSIDE_VPC + "}]}", invalid),
+ Arguments.of("a member of no statement", document("{\"Foo\":\"x\"," + DENY_OUTSIDE_VPC + "}"), invalid),
+ Arguments.of("no Effect", document("{\"Principal\":\"*\",\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}"),
+ invalid),
+ Arguments.of("an Effect of neither kind", document("{\"Effect\":\"Maybe\",\"Principal\":\"*\","
+ + "\"Resource\":\"*\"}"), invalid),
+ Arguments.of("no Principal", document("{\"Effect\":\"Deny\",\"Resource\":\"*\"}"), unreadable),
+ Arguments.of("NotPrincipal", document("{\"Effect\":\"Deny\",\"NotPrincipal\":{\"AWS\":\"*\"},"
+ + "\"Resource\":\"*\"}"), unreadable),
+ Arguments.of("no Resource", document("{\"Effect\":\"Deny\",\"Principal\":\"*\"}"), unreadable),
+ Arguments.of("NotResource", document("{\"Effect\":\"Deny\",\"Principal\":\"*\",\"NotResource\":\"*\"}"),
+ unreadable),
+ Arguments.of("a principal of text", document("{\"Effect\":\"Deny\",\"Principal\":\"foo\",\"Resource\":\"*\"}"),
+ invalid),
+ Arguments.of("every service", document("{\"Effect\":\"Deny\",\"Principal\":{\"Service\":\"*\"},"
+ + "\"Resource\":\"*\"}"), invalid),
+ Arguments.of("a service", document("{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"*\",\"Service\":"
+ + "\"dsql.amazonaws.com\"},\"Resource\":\"*\"}"), DsqlClusterPolicies.SERVICE_PRINCIPAL),
+ Arguments.of("a canonical user", document("{\"Effect\":\"Deny\",\"Principal\":{\"CanonicalUser\":\"abc\"},"
+ + "\"Resource\":\"*\"}"), invalid),
+ Arguments.of("a role that does not exist", document("{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":"
+ + "\"arn:aws:iam::" + ACCOUNT + ":role/missing\"},\"Resource\":\"*\"}"), invalid),
+ Arguments.of("an operator of no case", document("{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Resource\":\"*\","
+ + "\"Condition\":{\"stringequals\":{\"aws:SourceVpc\":\"vpc-1\"}}}"), invalid),
+ Arguments.of("an operator of no kind", document("{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Resource\":\"*\","
+ + "\"Condition\":{\"Foo\":{\"aws:SourceVpc\":\"vpc-1\"}}}"), invalid));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("allowsToEveryone")
+ void anAllowToEveryoneIsPublicUnlessAConditionRestrictsIt(String condition, boolean isPublic) {
+ String policy = document("{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"dsql:DbConnect\","
+ + "\"Resource\":\"*\"" + (condition == null ? "" : ",\"Condition\":" + condition) + "}");
+
+ assertEquals(isPublic, DsqlClusterPolicies.grantsPublicAccess(MAPPER, kept(policy)));
+ }
+
+ static Stream<Arguments> allowsToEveryone() {
+ String role = "arn:aws:iam::" + ACCOUNT + ":role/x";
+ return Stream.of(
+ Arguments.of(null, true),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpc\":\"vpc-1\"}}", false),
+ Arguments.of("{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-1\"}}", true),
+ Arguments.of("{\"StringEqualsIfExists\":{\"aws:SourceVpc\":\"vpc-1\"}}", true),
+ Arguments.of("{\"ForAnyValue:StringEquals\":{\"aws:SourceVpc\":\"vpc-1\"}}", false),
+ Arguments.of("{\"ForAllValues:StringEquals\":{\"aws:SourceVpc\":\"vpc-1\"}}", true),
+ Arguments.of("{\"StringEqualsIgnoreCase\":{\"aws:SourceVpc\":\"vpc-1\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"AWS:SOURCEVPC\":\"vpc-1\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpc\":[\"vpc-1\",\"*\"]}}", false),
+ Arguments.of("{\"StringLike\":{\"aws:SourceVpc\":\"vpc-*\"}}", true),
+ Arguments.of("{\"StringLike\":{\"aws:SourceVpc\":[\"vpc-1\",\"vpc-2\"]}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalAccount\":\"*\"}}", false),
+ Arguments.of("{\"StringLike\":{\"aws:PrincipalAccount\":\"*\"}}", true),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalOrgID\":\"o-abc\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalOrgPaths\":\"o-a/r-b/ou-c/\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceAccount\":\"" + ACCOUNT + "\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceOwner\":\"" + ACCOUNT + "\"}}", true),
+ Arguments.of("{\"StringEquals\":{\"aws:userid\":\"AIDAEXAMPLE\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpce\":\"vpce-1\"}}", false),
+ Arguments.of("{\"StringLike\":{\"aws:SourceArn\":\"*\"}}", true),
+ Arguments.of("{\"StringLike\":{\"aws:SourceArn\":\"" + role + "\"}}", false),
+ Arguments.of("{\"StringLike\":{\"aws:SourceArn\":\"arn:aws:iam::" + ACCOUNT + ":role/*\"}}", false),
+ Arguments.of("{\"StringLike\":{\"aws:SourceArn\":\"arn:aws:iam::*:role/x\"}}", true),
+ Arguments.of("{\"StringLike\":{\"aws:PrincipalArn\":\"*\"}}", true),
+ Arguments.of("{\"ArnLike\":{\"aws:SourceArn\":\"*\"}}", false),
+ Arguments.of("{\"ArnLike\":{\"aws:SourceArn\":\"arn:aws:*\"}}", false),
+ Arguments.of("{\"ArnLike\":{\"aws:PrincipalArn\":\"*\"}}", false),
+ Arguments.of("{\"ArnLike\":{\"aws:PrincipalArn\":\"arn:aws:iam::*:role/x\"}}", true),
+ Arguments.of("{\"ArnLike\":{\"aws:PrincipalArn\":\"" + role + "\"}}", false),
+ Arguments.of("{\"ArnEquals\":{\"aws:SourceArn\":\"*\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceIp\":\"10.0.0.1\"}}", false),
+ Arguments.of("{\"IpAddress\":{\"aws:SourceIp\":\"10.0.0.0/8\"}}", false),
+ Arguments.of("{\"IpAddress\":{\"aws:SourceIp\":\"10.0.0.0/7\"}}", true),
+ Arguments.of("{\"IpAddress\":{\"aws:SourceIp\":\"0.0.0.0/0\"}}", true),
+ Arguments.of("{\"NotIpAddress\":{\"aws:SourceIp\":\"10.0.0.0/8\"}}", true),
+ Arguments.of("{\"Bool\":{\"aws:SecureTransport\":\"true\"}}", true),
+ Arguments.of("{\"Bool\":{\"aws:PrincipalIsAWSService\":\"true\"}}", false),
+ Arguments.of("{\"Bool\":{\"aws:PrincipalIsAWSService\":\"false\"}}", true),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpc\":\"vpc-1\"},\"Bool\":{\"aws:SecureTransport\":\"true\"}}",
+ false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpcArn\":\"arn:aws:ec2:eu-west-1:" + ACCOUNT + ":vpc/vpc-1\"}}",
+ false),
+ Arguments.of("{\"StringEquals\":{\"aws:VpceAccount\":\"" + ACCOUNT + "\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:VpceOrgID\":\"o-abc\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:VpceOrgPaths\":\"o-a/r-b/ou-c/\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalServiceName\":\"lambda.amazonaws.com\"}}", false),
+ Arguments.of("{\"ForAnyValue:StringEquals\":{\"aws:PrincipalServiceNamesList\":\"lambda.amazonaws.com\"}}",
+ false),
+ Arguments.of("{\"StringEquals\":{\"aws:Ec2InstanceSourceVpc\":\"vpc-1\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceOrgID\":\"o-abc\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceOrgPaths\":\"o-a/r-b/ou-c/\"}}", false),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalArn\":\"${aws:PrincipalArn}\"}}", true),
+ Arguments.of("{\"StringEquals\":{\"aws:SourceVpc\":\"${aws:SourceVpc}\"}}", true),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::" + ACCOUNT + ":role/${aws:username}\"}}",
+ true),
+ Arguments.of("{\"StringEquals\":{\"aws:PrincipalAccount\":[\"" + ACCOUNT + "\",\"${aws:PrincipalAccount}\"]}}",
+ true),
+ Arguments.of("{\"ArnEquals\":{\"aws:SourceArn\":\"${aws:SourceArn}\"}}", false));
+ }
+
+ @Test
+ void onlyAWildcardOfTheAwsKindGrantsToEveryone() {
+ String allow = "\"Effect\":\"Allow\",\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"";
+
+ assertEquals(true, isPublic(document("{" + allow + ",\"Principal\":{\"AWS\":[\"*\",\"" + ACCOUNT + "\"]}}")));
+ assertEquals(false, isPublic(document("{" + allow + ",\"Principal\":{\"Federated\":\"*\"}}")));
+ assertEquals(false, isPublic(document("{" + allow + ",\"Principal\":{\"AWS\":\"" + ACCOUNT + "\"}}")));
+ assertEquals(true, isPublic("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":\"*\","
+ + "\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"},{" + allow + ",\"Principal\":\"*\"}]}"));
+ }
+
+ private static boolean isPublic(String policy) {
+ return DsqlClusterPolicies.grantsPublicAccess(MAPPER, kept(policy));
+ }
+
+ private static String kept(String policy) {
+ return DsqlClusterPolicies.canonical(MAPPER, policy, "aws",
+ arn -> arn.endsWith(":root") || arn.endsWith(":role/x"));
+ }
+
+ private static String document(String statement) {
+ return document(statement, "2012-10-17");
+ }
+
+ private static String document(String statement, String version) {
+ return "{\"Version\":\"" + version + "\",\"Statement\":[" + statement + "]}";
+ }
+
+ private static String compact(String json) {
+ try {
+ return MAPPER.readTree(json).toString();
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlIntegrationTest.java
new file mode 100644
index 0000000000..38e00ed27a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlIntegrationTest.java
@@ -0,0 +1,318 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.matchesPattern;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Aurora DSQL's control plane over its REST-JSON paths, with the answers measured on AWS
+ * (eu-west-1, 2026-10-16 and 2026-10-20). Clusters have no database behind them, so they are ACTIVE at once.
+ */
+@QuarkusTest
+class DsqlIntegrationTest {
+
+ private static final String ACCOUNT = "111122223333";
+ private static final String ROOT = "arn:aws:iam::" + ACCOUNT + ":root";
+ private static final String DENY_OUTSIDE_VPC = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\",\"Condition\":"
+ + "{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}}]}";
+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ + "/20261016/eu-west-1/dsql/aws4_request, SignedHeaders=host, Signature=abc";
+
+ @Test
+ void aClusterIsCreatedProtectedReadUpdatedAndDeleted() {
+ String identifier = dsql().body(Map.of("tags", Map.of("Purpose", "test")))
+ .post("/cluster").then().statusCode(200)
+ .body("identifier", matchesPattern("[a-z2-7]{26}"))
+ .body("arn", matchesPattern("arn:aws:dsql:eu-west-1:" + ACCOUNT + ":cluster/[a-z2-7]{26}"))
+ .body("status", equalTo("CREATING"))
+ .body("creationTime", instanceOf(Number.class))
+ .body("encryptionDetails.encryptionType", equalTo("AWS_OWNED_KMS_KEY"))
+ .body("encryptionDetails.encryptionStatus", equalTo("ENABLED"))
+ .body("deletionProtectionEnabled", equalTo(true))
+ .extract().path("identifier");
+
+ dsql().get("/cluster/" + identifier).then().statusCode(200)
+ .body("status", equalTo("ACTIVE"))
+ .body("tags.Purpose", equalTo("test"))
+ .body("endpoint", equalTo(identifier + ".dsql.eu-west-1.localhost.floci.io"));
+ dsql().get("/cluster").then().statusCode(200)
+ .body("clusters.identifier", hasItem(identifier));
+
+ dsql().delete("/cluster/" + identifier).then().statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("Can't delete cluster: Deletion protection is enabled. To proceed,"
+ + " disable deletion protection and try again."))
+ .body("reason", equalTo("deletionProtectionEnabled"));
+
+ dsql().body(Map.of("deletionProtectionEnabled", false)).post("/cluster/" + identifier)
+ .then().statusCode(200)
+ .body("status", equalTo("UPDATING"))
+ .body("deletionProtectionEnabled", nullValue());
+ dsql().get("/cluster/" + identifier).then().statusCode(200)
+ .body("status", equalTo("ACTIVE"))
+ .body("deletionProtectionEnabled", equalTo(false));
+
+ dsql().delete("/cluster/" + identifier).then().statusCode(200)
+ .body("status", equalTo("DELETING"));
+ dsql().get("/cluster/" + identifier).then().statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"))
+ .body("resourceType", equalTo("cluster"));
+ }
+
+ @Test
+ void identifiersAreCheckedAsDsqlChecksThem() {
+ dsql().get("/cluster/abc").then().statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value at 'identifier' failed to satisfy"
+ + " constraint: Member must satisfy regular expression pattern: [a-z0-9]{26}"));
+ dsql().get("/cluster/abcdefghijklmnopqrstuvwxyz").then().statusCode(400)
+ .body("message", equalTo("Invalid input 'identifier: abcdefghijklmnopqrstuvwxyz'. The cluster"
+ + " identifier format is invalid. Provide a valid cluster identifier and try again."));
+ dsql().get("/cluster/aaaaaaaaaaaaaaaaaaaaaaaaaa").then().statusCode(404)
+ .body("message", equalTo("The resource with ARN arn:aws:dsql:eu-west-1:" + ACCOUNT
+ + ":cluster/aaaaaaaaaaaaaaaaaaaaaaaaaa doesn't exist. Verify the ARN and try again."))
+ .body("resourceId", equalTo("aaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ }
+
+ @Test
+ void aClientTokenMakesCreateIdempotent() {
+ String first = dsql().body(Map.of("clientToken", "same-request", "deletionProtectionEnabled", false))
+ .post("/cluster").then().statusCode(200).extract().path("identifier");
+ dsql().body(Map.of("clientToken", "same-request", "deletionProtectionEnabled", false))
+ .post("/cluster").then().statusCode(200).body("identifier", equalTo(first));
+ // Measured (eu-west-1, 2026-10-20): the same token with other parameters is a conflict.
+ dsql().body(Map.of("clientToken", "same-request", "deletionProtectionEnabled", true))
+ .post("/cluster").then().statusCode(409)
+ .body("message", equalTo("Requests using a client token should supply identical request parameters"));
+ dsql().delete("/cluster/" + first).then().statusCode(200);
+ }
+
+ /**
+ * Measured (eu-west-1, 2026-10-20): text is false when it spells false in any case and true
+ * otherwise; empty text, a number and an object fail to deserialize.
+ */
+ @Test
+ void deletionProtectionIsReadAsDsqlReadsIt() {
+ String yes = dsql().body(Map.of("deletionProtectionEnabled", "yes")).post("/cluster")
+ .then().statusCode(200).body("deletionProtectionEnabled", equalTo(true)).extract().path("identifier");
+ dsql().body(Map.of("deletionProtectionEnabled", "False")).post("/cluster/" + yes).then().statusCode(200);
+ dsql().get("/cluster/" + yes).then().body("deletionProtectionEnabled", equalTo(false));
+ dsql().body(Map.of("deletionProtectionEnabled", "TRUE")).post("/cluster/" + yes).then().statusCode(200);
+ dsql().get("/cluster/" + yes).then().body("deletionProtectionEnabled", equalTo(true));
+
+ dsql().body(Map.of("deletionProtectionEnabled", 1)).post("/cluster").then().statusCode(400)
+ .body("message", equalTo("NUMBER_VALUE cannot be converted to Boolean"));
+ dsql().body(Map.of("deletionProtectionEnabled", Map.of())).post("/cluster").then().statusCode(400)
+ .body("message", equalTo("Start of structure or map found where not expected"));
+ dsql().body(Map.of("deletionProtectionEnabled", "")).post("/cluster/" + yes).then().statusCode(400)
+ .body("message", equalTo("Unexpected token received from parser"));
+
+ dsql().body(Map.of("deletionProtectionEnabled", false)).post("/cluster/" + yes).then().statusCode(200);
+ dsql().delete("/cluster/" + yes).then().statusCode(200);
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): AWS_OWNED_KMS_KEY names AWS's own key, on create and update. */
+ @Test
+ void theReservedAwsOwnedKeyIsAwsOwned() {
+ String identifier = dsql().body(Map.of("deletionProtectionEnabled", false, "kmsEncryptionKey", "AWS_OWNED_KMS_KEY"))
+ .post("/cluster").then().statusCode(200)
+ .body("encryptionDetails.encryptionType", equalTo("AWS_OWNED_KMS_KEY")).extract().path("identifier");
+ dsql().body(Map.of("kmsEncryptionKey", "AWS_OWNED_KMS_KEY")).post("/cluster/" + identifier).then().statusCode(200);
+ dsql().get("/cluster/" + identifier).then()
+ .body("encryptionDetails.encryptionType", equalTo("AWS_OWNED_KMS_KEY"))
+ .body("encryptionDetails.kmsKeyArn", nullValue());
+ dsql().delete("/cluster/" + identifier).then().statusCode(200);
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): the next page carries on after its first cluster is deleted. */
+ @Test
+ void aPageCarriesOnAfterItsNextClusterIsGone() {
+ String auth = AUTH.replace("eu-west-1", "ap-southeast-4");
+ for (int i = 0; i < 3; i++) {
+ given().header("Authorization", auth).contentType("application/json")
+ .body(Map.of("deletionProtectionEnabled", false)).post("/cluster")
+ .then().statusCode(200);
+ }
+ List<String> order = given().header("Authorization", auth).get("/cluster")
+ .then().statusCode(200).extract().jsonPath().getList("clusters.identifier", String.class);
+ assertEquals(3, order.size());
+ String token = given().header("Authorization", auth).queryParam("max-results", 1).get("/cluster")
+ .then().statusCode(200).body("clusters[0].identifier", equalTo(order.get(0))).extract().path("nextToken");
+ given().header("Authorization", auth).delete("/cluster/" + order.get(1)).then().statusCode(200);
+ given().header("Authorization", auth).queryParam("max-results", 1).queryParam("next-token", token).get("/cluster")
+ .then().statusCode(200).body("clusters[0].identifier", equalTo(order.get(2)));
+ given().header("Authorization", auth).delete("/cluster/" + order.get(0)).then().statusCode(200);
+ given().header("Authorization", auth).delete("/cluster/" + order.get(2)).then().statusCode(200);
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): another account's cluster ARN is refused, not read in the caller's. */
+ @Test
+ void anotherAccountsArnIsRefused() {
+ String identifier = dsql().body(Map.of("deletionProtectionEnabled", false)).post("/cluster")
+ .then().statusCode(200).extract().path("identifier");
+ String foreign = "arn:aws:dsql:eu-west-1:999999999999:cluster/" + identifier;
+ dsql().urlEncodingEnabled(false).get("/tags/" + URLEncoder.encode(foreign, StandardCharsets.UTF_8))
+ .then().statusCode(403)
+ .body("message", equalTo("User: " + ROOT + " is not authorized to perform: dsql:ListTagsForResource on"
+ + " resource: " + foreign + " because no resource-based policy allows the"
+ + " dsql:ListTagsForResource action"));
+ dsql().delete("/cluster/" + identifier).then().statusCode(200);
+ }
+
+ @Test
+ void tagsPoliciesAndTheVpcEndpointServiceName() {
+ String identifier = dsql().body(Map.of("deletionProtectionEnabled", false))
+ .post("/cluster").then().statusCode(200).extract().path("identifier");
+ String arn = "arn:aws:dsql:eu-west-1:" + ACCOUNT + ":cluster/" + identifier;
+ String tagsPath = "/tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8);
+
+ dsql().body(Map.of("tags", Map.of("team", "data"))).urlEncodingEnabled(false)
+ .post(tagsPath).then().statusCode(200);
+ dsql().urlEncodingEnabled(false).get(tagsPath).then().statusCode(200)
+ .body("tags.team", equalTo("data"));
+ dsql().urlEncodingEnabled(false).queryParam("tagKeys", "team")
+ .delete(tagsPath).then().statusCode(200);
+ dsql().urlEncodingEnabled(false).get(tagsPath).then().statusCode(200)
+ .body("tags", not(hasKey("team")));
+
+ dsql().get("/clusters/" + identifier + "/vpc-endpoint-service-name").then().statusCode(200)
+ .body("serviceName", matchesPattern("com\\.amazonaws\\.eu-west-1\\.dsql-[a-z2-7]{4}"))
+ .body("clusterVpcEndpoint", matchesPattern(identifier + "\\.dsql-[a-z2-7]{4}\\.eu-west-1\\..+"));
+
+ // Measured (eu-west-1, 2026-10-20): a version is when the policy was set, the policy is kept in
+ // DSQL's own form, and a delete answers the version it deleted.
+ String version = dsql().body(Map.of("policy", DENY_OUTSIDE_VPC))
+ .post("/cluster/" + identifier + "/policy").then().statusCode(200)
+ .body("policyVersion", matchesPattern("\\d{13}")).extract().path("policyVersion");
+ dsql().get("/cluster/" + identifier + "/policy").then().statusCode(200)
+ .body("policy", equalTo("""
+ {
+ "Version" : "2012-10-17",
+ "Statement" : [ {
+ "Effect" : "Deny",
+ "Principal" : {
+ "AWS" : "*"
+ },
+ "Action" : "dsql:DbConnect",
+ "Resource" : "*",
+ "Condition" : {
+ "StringNotEquals" : {
+ "aws:SourceVpc" : "vpc-0123456789abcdef0"
+ }
+ }
+ } ]
+ }"""))
+ .body("policyVersion", equalTo(version));
+ dsql().delete("/cluster/" + identifier + "/policy").then().statusCode(200)
+ .body("policyVersion", equalTo(version));
+ dsql().get("/cluster/" + identifier + "/policy").then().statusCode(404)
+ .body("message", equalTo("Aurora DSQL can't find the policy for the resource " + identifier
+ + ". Verify that the policy exists."))
+ .body("resourceType", equalTo("policy"));
+
+ dsql().delete("/cluster/" + identifier).then().statusCode(200);
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): the three ways a tag call is refused before it finds a cluster. */
+ @Test
+ void aTagCallRefusesWhatIsNoClusterOfTheRegion() {
+ String malformed = "arn:aws:dsql:eu-west-1:" + ACCOUNT + ":cluster/abc";
+ String otherRegion = "arn:aws:dsql:us-east-1:" + ACCOUNT + ":cluster/aaaaaaaaaaaaaaaaaaaaaaaaaa";
+ String missing = "arn:aws:dsql:eu-west-1:" + ACCOUNT + ":cluster/aaaaaaaaaaaaaaaaaaaaaaaaaa";
+
+ dsql().urlEncodingEnabled(false).get("/tags/" + URLEncoder.encode(malformed, StandardCharsets.UTF_8))
+ .then().statusCode(403)
+ .body("__type", equalTo("AccessDeniedException"))
+ .body("message", equalTo("Invalid input for 'resourceArn'. The cluster ARN that you specified isn't"
+ + " valid. Provide the cluster ARN in the format"
+ + " 'arn:partition:dsql:region:account-id:cluster/cluster-id' and try again.User: " + ROOT
+ + " is not authorized to perform: dsql:ListTagsForResource on resource: * with an explicit deny"
+ + " in a resource-based policy"));
+ dsql().urlEncodingEnabled(false).get("/tags/" + URLEncoder.encode(otherRegion, StandardCharsets.UTF_8))
+ .then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid input resource arn: expected region eu-west-1"));
+ dsql().urlEncodingEnabled(false).get("/tags/" + URLEncoder.encode(missing, StandardCharsets.UTF_8))
+ .then().statusCode(404)
+ .body("__type", equalTo("NotFoundException"))
+ .body("message", equalTo("Resource was not found"));
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): only the page token's refusal names a reason and the member. */
+ @Test
+ void listingRefusesWhatItCannotPage() {
+ dsql().queryParam("next-token", "garbage").get("/cluster").then().statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("Invalid pagination token. Request a new token and try again."))
+ .body("reason", equalTo("fieldValidationFailed"))
+ .body("fieldList[0].name", equalTo("next-token"))
+ .body("fieldList[0].message", equalTo("Invalid pagination token. Request a new token and try again."));
+ dsql().queryParam("max-results", 0).get("/cluster").then().statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value at 'maxResults' failed to satisfy"
+ + " constraint: Member must have value greater than or equal to 1"))
+ .body("reason", nullValue());
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): what PutClusterPolicy refuses, and the lockout it can be told to allow. */
+ @Test
+ void aPolicyIsRefusedAsDsqlRefusesIt() {
+ String identifier = dsql().body(Map.of("deletionProtectionEnabled", false)).post("/cluster")
+ .then().statusCode(200).extract().path("identifier");
+ String policyPath = "/cluster/" + identifier + "/policy";
+ String lockout = DENY_OUTSIDE_VPC.replace("\"dsql:DbConnect\"", "\"*\"");
+
+ dsql().body(Map.of("policy", "")).post(policyPath).then().statusCode(400)
+ .body("message", equalTo("1 validation error detected: Value at 'policy' failed to satisfy constraint:"
+ + " Member must have length greater than or equal to 1"));
+ dsql().body(Map.of("policy", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\",\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}]}"))
+ .post(policyPath).then().statusCode(400)
+ .body("message", equalTo("Aurora DSQL can't apply the policy because it grants public access. Modify"
+ + " the policy to restrict access and try again."));
+ dsql().body(Map.of("policy", lockout)).post(policyPath).then().statusCode(400)
+ .body("message", equalTo("The new policy would result in the calling principal being unable to"
+ + " further update and delete this cluster's policy. Set the 'bypassPolicyLockoutSafetyCheck'"
+ + " parameter to 'true' to confirm this intent."));
+ dsql().body(Map.of("policy", lockout, "bypassPolicyLockoutSafetyCheck", true)).post(policyPath)
+ .then().statusCode(200);
+
+ dsql().delete("/cluster/" + identifier).then().statusCode(200);
+ }
+
+ /** Measured (eu-west-1, 2026-10-20): a multi-Region cluster waits for its peers, and so does its deletion. */
+ @Test
+ void aMultiRegionClusterWaitsForItsPeers() {
+ String arn = dsql().body(Map.of("deletionProtectionEnabled", false,
+ "multiRegionProperties", Map.of("witnessRegion", "eu-west-2")))
+ .post("/cluster").then().statusCode(200)
+ .body("status", equalTo("PENDING_SETUP"))
+ .extract().path("arn");
+ String identifier = arn.substring(arn.lastIndexOf('/') + 1);
+
+ dsql().get("/cluster/" + identifier).then().statusCode(200)
+ .body("status", equalTo("PENDING_SETUP"))
+ .body("multiRegionProperties.witnessRegion", equalTo("eu-west-2"))
+ .body("multiRegionProperties.clusters", equalTo(List.of(arn)));
+ dsql().delete("/cluster/" + identifier).then().statusCode(200)
+ .body("status", equalTo("PENDING_DELETE"));
+ }
+
+ private static RequestSpecification dsql() {
+ return given().header("Authorization", AUTH).contentType("application/json");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlServiceTest.java
new file mode 100644
index 0000000000..159c2f94d3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlServiceTest.java
@@ -0,0 +1,212 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The control plane in isolation, with the answers measured on AWS (eu-west-1, 2026-10-20):
+ * policy versions and refusals, the lockout check, tag calls on what is no cluster of the Region,
+ * multi-Region peering, and updates that leave out a member.
+ */
+class DsqlServiceTest {
+
+ private static final String ACCOUNT = "111122223333";
+ private static final String REGION = "eu-west-1";
+ private static final String ROOT = "arn:aws:iam::" + ACCOUNT + ":root";
+
+ private final DsqlPrincipals principals = mock(DsqlPrincipals.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final DsqlService service = new DsqlService(
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT),
+ new RegionResolver(REGION, ACCOUNT), "localhost.floci.io", new DsqlDataPlane(), principals,
+ new IamPolicyEvaluator(mapper), mapper);
+
+ @BeforeEach
+ void caller() {
+ when(principals.caller()).thenReturn(CallerArns.accountRoot(ROOT, ACCOUNT));
+ when(principals.exists(anyString())).thenAnswer(call -> call.getArgument(0, String.class).endsWith(":root"));
+ }
+
+ @Test
+ void aPolicyVersionIsWhenThePolicyWasSet() {
+ String id = cluster().getIdentifier();
+ long before = Instant.now().toEpochMilli();
+
+ String first = service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), null, false);
+ String second = service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), first, false);
+
+ assertTrue(Long.parseLong(first) >= before);
+ assertTrue(Long.parseLong(second) > Long.parseLong(first));
+ assertEquals(second, service.getClusterPolicy(REGION, id).getPolicyVersion());
+ assertEquals(second, service.deleteClusterPolicy(REGION, id, null));
+ AwsException none = assertThrows(AwsException.class, () -> service.getClusterPolicy(REGION, id));
+ assertEquals("ResourceNotFoundException", none.getErrorCode());
+ assertEquals("Aurora DSQL can't find the policy for the resource " + id + ". Verify that the policy exists.",
+ none.getMessage());
+ assertEquals(Map.of("resourceId", id, "resourceType", "policy"), none.getExtendedData());
+ }
+
+ @Test
+ void aVersionThatIsNotTheCurrentPolicysIsRefused() {
+ String id = cluster().getIdentifier();
+ String noVersion = "Aurora DSQL can't find policy version 1 for resource " + id
+ + ". Verify that the policy exists and that the version is correct.";
+
+ AwsException noPolicy = assertThrows(AwsException.class,
+ () -> service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), "1", false));
+ assertEquals("ResourceNotFoundException", noPolicy.getErrorCode());
+ assertEquals(noVersion, noPolicy.getMessage());
+ service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), null, false);
+ AwsException conflict = assertThrows(AwsException.class,
+ () -> service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), "1", false));
+ assertEquals("ConflictException", conflict.getErrorCode());
+ assertEquals(noVersion, conflict.getMessage());
+ assertEquals("cluster", conflict.getExtendedData().get("resourceType"));
+ AwsException delete = assertThrows(AwsException.class, () -> service.deleteClusterPolicy(REGION, id, "1"));
+ assertEquals("ResourceNotFoundException", delete.getErrorCode());
+ assertEquals("policy", delete.getExtendedData().get("resourceType"));
+
+ String current = service.getClusterPolicy(REGION, id).getPolicyVersion();
+ service.deleteClusterPolicy(REGION, id, current);
+ AwsException deleted = assertThrows(AwsException.class,
+ () -> service.putClusterPolicy(REGION, id, deny("dsql:DbConnect"), current, false));
+ assertEquals("ResourceNotFoundException", deleted.getErrorCode());
+ assertEquals("Aurora DSQL can't find policy version " + current + " for resource " + id
+ + ". Verify that the policy exists and that the version is correct.", deleted.getMessage());
+ }
+
+ @Test
+ void aPolicyThatLocksTheCallerOutOfBothPolicyActionsIsRefused() {
+ String id = cluster().getIdentifier();
+
+ AwsException lockout = assertThrows(AwsException.class, () -> service.putClusterPolicy(REGION, id,
+ deny("[\"dsql:PutClusterPolicy\",\"dsql:DeleteClusterPolicy\"]"), null, false));
+ assertEquals(DsqlService.LOCKOUT, lockout.getMessage());
+ service.putClusterPolicy(REGION, id, deny("\"dsql:PutClusterPolicy\""), null, false);
+ service.putClusterPolicy(REGION, id, deny("\"*\""), null, true);
+ AwsException onCreate = assertThrows(AwsException.class, () -> service.createCluster(REGION, false, null,
+ null, null, null, null, deny("\"*\""), false));
+ assertEquals(DsqlService.LOCKOUT, onCreate.getMessage());
+ }
+
+ @Test
+ void aPublicPolicyIsRefused() {
+ AwsException refused = assertThrows(AwsException.class, () -> service.createCluster(REGION, false, null, null,
+ null, null, null, "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","
+ + "\"Action\":\"dsql:DbConnect\",\"Resource\":\"*\"}]}", false));
+
+ assertEquals(DsqlClusterPolicies.PUBLIC, refused.getMessage());
+ assertEquals(0, service.listClusters(REGION, null, null).clusters().size());
+ }
+
+ @Test
+ void aTagCallRefusesWhatIsNoClusterOfTheRegion() {
+ DsqlCluster cluster = cluster();
+ String missing = "arn:aws:dsql:" + REGION + ":" + ACCOUNT + ":cluster/aaaaaaaaaaaaaaaaaaaaaaaaaa";
+
+ AwsException invalid = assertThrows(AwsException.class,
+ () -> service.listTags(REGION, "arn:aws:dsql:" + REGION + ":" + ACCOUNT + ":cluster/abc"));
+ assertEquals("AccessDeniedException", invalid.getErrorCode());
+ assertEquals(403, invalid.getHttpStatus());
+ assertEquals("Invalid input for 'resourceArn'. The cluster ARN that you specified isn't valid. Provide the"
+ + " cluster ARN in the format 'arn:partition:dsql:region:account-id:cluster/cluster-id' and try"
+ + " again.User: " + ROOT + " is not authorized to perform: dsql:ListTagsForResource on resource: *"
+ + " with an explicit deny in a resource-based policy", invalid.getMessage());
+ AwsException otherRegion = assertThrows(AwsException.class,
+ () -> service.tagResource("us-east-1", cluster.getArn(), Map.of("k", "v")));
+ assertEquals("BadRequestException", otherRegion.getErrorCode());
+ assertEquals("Invalid input resource arn: expected region us-east-1", otherRegion.getMessage());
+ AwsException notFound = assertThrows(AwsException.class,
+ () -> service.untagResource(REGION, missing, List.of("k")));
+ assertEquals("NotFoundException", notFound.getErrorCode());
+ assertEquals("Resource was not found", notFound.getMessage());
+ }
+
+ @Test
+ void multiRegionClustersWaitUntilEachNamesTheOther() {
+ DsqlCluster first = service.createCluster(REGION, false, null, null, null, "eu-west-2", null, null, false);
+ DsqlCluster second = service.createCluster("eu-west-3", false, null, null, null, "eu-west-2", null, null, false);
+ assertEquals(DsqlService.PENDING_SETUP, first.getStatus());
+ assertEquals(List.of(first.getArn()), first.getLinkedClusterArns());
+
+ service.updateCluster(REGION, first.getIdentifier(), null, null, null, List.of(second.getArn()));
+ assertEquals(List.of(second.getArn(), first.getArn()),
+ service.getCluster(REGION, first.getIdentifier()).getLinkedClusterArns());
+ assertEquals(DsqlService.PENDING_SETUP, service.getCluster(REGION, first.getIdentifier()).getStatus());
+
+ service.updateCluster("eu-west-3", second.getIdentifier(), null, null, null, List.of(first.getArn()));
+ assertEquals(DsqlService.ACTIVE, service.getCluster(REGION, first.getIdentifier()).getStatus());
+ assertEquals(DsqlService.ACTIVE, service.getCluster("eu-west-3", second.getIdentifier()).getStatus());
+ assertEquals(List.of(first.getArn(), second.getArn()),
+ service.getCluster("eu-west-3", second.getIdentifier()).getLinkedClusterArns());
+ }
+
+ @Test
+ void anUpdateLeavesWhatItDoesNotNameAsItWas() {
+ DsqlCluster cluster = service.createCluster(REGION, false, "arn:aws:kms:eu-west-1:" + ACCOUNT + ":key/k",
+ null, null, "eu-west-2", null, null, false);
+
+ service.updateCluster(REGION, cluster.getIdentifier(), null, null, null, null);
+
+ DsqlCluster updated = service.getCluster(REGION, cluster.getIdentifier());
+ assertEquals(false, updated.isDeletionProtectionEnabled());
+ assertEquals("arn:aws:kms:eu-west-1:" + ACCOUNT + ":key/k", updated.getKmsEncryptionKey());
+ assertEquals("eu-west-2", updated.getWitnessRegion());
+ assertEquals(List.of(cluster.getArn()), updated.getLinkedClusterArns());
+ }
+
+ @Test
+ void aCloudFormationUpdateKeepsAPolicyItAlreadyHas() {
+ String id = cluster().getIdentifier();
+ String version = service.putClusterPolicy(REGION, id, deny("\"dsql:DbConnect\""), null, false);
+
+ service.replaceClusterPolicy(REGION, id, deny("[\"dsql:DbConnect\"]"));
+ assertEquals(version, service.getCluster(REGION, id).getPolicyVersion());
+ service.replaceClusterPolicy(REGION, id, null);
+ assertNull(service.getCluster(REGION, id).getPolicy());
+ }
+
+ @Test
+ void listingRefusesWhatItCannotPage() {
+ AwsException token = assertThrows(AwsException.class, () -> service.listClusters(REGION, null, "garbage"));
+ assertEquals("Invalid pagination token. Request a new token and try again.", token.getMessage());
+ assertEquals(Map.of("reason", "fieldValidationFailed", "fieldList", List.of(Map.of("name", "next-token",
+ "message", "Invalid pagination token. Request a new token and try again."))), token.getExtendedData());
+ AwsException tooMany = assertThrows(AwsException.class, () -> service.listClusters(REGION, 101, null));
+ assertEquals("1 validation error detected: Value at 'maxResults' failed to satisfy constraint: Member must"
+ + " have value less than or equal to 100", tooMany.getMessage());
+ assertNull(tooMany.getExtendedData());
+ }
+
+ private DsqlCluster cluster() {
+ return service.createCluster(REGION, false, null, null, null, null, null, null, false);
+ }
+
+ /** A Deny to everyone outside one VPC, which the caller is not in. */
+ private static String deny(String action) {
+ String actions = action.startsWith("[") || action.startsWith("\"") ? action : "\"" + action + "\"";
+ return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"*\"},"
+ + "\"Action\":" + actions + ",\"Resource\":\"*\",\"Condition\":{\"StringNotEquals\":"
+ + "{\"aws:SourceVpc\":\"vpc-0123456789abcdef0\"}}}]}";
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index d283e045fc..ae85494a1f 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -229,6 +229,8 @@ floci:
enabled: true
transaction-ttl-seconds: 180
database-resuming-exception-enabled: false
+ dsql:
+ enabled: true
redshift-data:
enabled: true
result-ttl-hours: 24
diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
index 38e038d4cb..6f9b222ccf 100644
--- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
+++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
@@ -3,6 +3,7 @@ AWS::BedrockAgentCore::Runtime WorkloadIdentityDetails the dotted WorkloadIdenti
AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses
AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci
AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name
+AWS::DSQL::Cluster EncryptionDetails an object, which attributes as Floci keeps them (text) cannot hold; on AWS an output naming it fails with "Every Value member must be a string", and EncryptionDetails.EncryptionStatus is refused as no attribute of the schema
AWS::EC2::Instance State the dotted State.Code and State.Name are set instead, the form AWS's GetAtt exposes for the nested State object
AWS::EC2::NatGateway AutoProvisionZones availability-mode NAT gateways are not emulated
AWS::EC2::NatGateway AutoScalingIps availability-mode NAT gateways are not emulated
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 2a771626ad..ccf36a6e89 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -65,6 +65,7 @@ AWS::Cognito::UserPoolResourceServer CognitoResourceServerCfnProvisioner
AWS::Cognito::UserPoolUser CognitoUserPoolUserCfnProvisioner
AWS::Cognito::UserPoolUserToGroupAttachment CognitoUserPoolUserToGroupAttachmentCfnProvisioner
AWS::Config::ConfigRule ConfigCfnProvisioner
+AWS::DSQL::Cluster DsqlCfnProvisioner
AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner
AWS::DynamoDB::Table DynamoDbCfnProvisioner
AWS::EC2::EIP Ec2NetworkCfnProvisioner
diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py
index 9fac8881b8..80ad47e5de 100644
--- a/tools/aws/regen_cfn_property_types.py
+++ b/tools/aws/regen_cfn_property_types.py
@@ -50,9 +50,9 @@ ARCHIVE_URL = "https://schema.cloudformation.us-east-1.amazonaws.com/Cloudformat
FETCH_TIMEOUT_SECONDS = 60
# The resource types whose provisioners read their properties through CfnPropertyTypes.
-RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate",
- "AWS::ECS::TaskDefinition", "AWS::Events::Rule", "AWS::Lambda::Function",
- "AWS::Lambda::LayerVersion"]
+RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance",
+ "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::Events::Rule",
+ "AWS::Lambda::Function", "AWS::Lambda::LayerVersion"]
# The shared shape each scalar body is written as, inline; a definition keeps its own name.
SCALAR_SHAPES = {"string": "String", "integer": "Integer", "boolean": "Boolean", "double": "Double", "json": "Json"}
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index 3ca31b6a6b..ab2c2c731b 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -26,6 +26,7 @@ order:
- AWS::ECS
- AWS::EKS
- AWS::RDS
+ - AWS::DSQL
- AWS::ElastiCache
- AWS::Redshift
- AWS::RedshiftServerless
@@ -136,6 +137,7 @@ service_labels:
AWS::CodePipeline: CodePipeline
AWS::Cognito: Cognito
AWS::Config: Config
+ AWS::DSQL: Aurora DSQL
AWS::DynamoDB: DynamoDB
AWS::EC2: EC2
AWS::ECR: ECR
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 81ad712add..2644eaa67e 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -208,6 +208,10 @@ services:
doc: docs/services/docdb.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/docdb/DocDbQueryHandler.java, mode: switch }
+ - service: dsql
+ doc: docs/services/dsql.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java, mode: rest }
- service: efs
doc: docs/services/efs.md
sources: