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

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

The first half of #6014. Aurora DSQL's REST JSON control plane, with
the answers measured on AWS (eu-west-1): CreateCluster, GetCluster,
ListClusters, UpdateCluster, DeleteCluster, GetVpcEndpointServiceName,
the cluster policy calls and tagging on cluster ARNs. Identifiers are 26
characters of lowercase base32 as DSQL's are, and malformed or unknown
ones are refused with DSQL's messages; a cluster created without
deletionProtectionEnabled is protected, and deleting a protected one is
refused. CreateCluster answers CREATING and the cluster is ACTIVE right
after.

AWS::DSQL::Cluster waits for ACTIVE, returns the identifier from Ref
and Identifier, ResourceArn, Status, CreationTime, Endpoint, VpcEndpoint
and VpcEndpointServiceName through Fn::GetAtt, and a protected cluster
makes the stack's deletion fail, as on AWS.

A cluster has no database behind it here: its endpoint is named as on
AWS, <id>.dsql.<region>.localhost.floci.io, but not served. Serving it
is the second half of #6014, its own pull request.

* fix(dsql): answer the control plane's edge cases as DSQL does

Review of #6048, each answer measured on DSQL (eu-west-1) first:
- ListClusters carries on from a page token whose cluster was deleted
  in between, as AWS does: the token now holds the sort position of the
  next page's first cluster rather than its identifier.
- deletionProtectionEnabled is read as DSQL reads it: text is false
  when it spells false in any case and true otherwise; empty text, a
  number, an object and a list fail with SerializationException.
- The tag calls refuse another account's cluster ARN with 403
  AccessDeniedException instead of reading it in the caller's account.
- A client token reused with other parameters answers 409
  ConflictException; with the same ones, the earlier cluster.
- AWS_OWNED_KMS_KEY names AWS's own key on create and update.

AWS::DSQL::Cluster reads DeletionProtectionEnabled and PolicyDocument
with AWS::NoValue as left out, and an update that drops the
multi-Region properties clears them, as it already reset the key and
deletion protection. ListTagsForResource copies the tags under the
cluster's lock, and a cluster's lock goes with the cluster.

* fix(dsql): answer errors, policies, updates and multi-Region clusters as DSQL does

A review asked for the attribute coverage, the reason ValidationException
carries, a real untag assertion and tests of the stack-update path.
Measuring them on DSQL (eu-west-1, 2026-10-20) found more that did not
match, fixed here too.

- Attributes are written with resource.getAttributes().put, which the
  schema coverage test reads; EncryptionDetails, an object an output
  refuses on AWS, is recorded as a gap.
- DSQL leaves reason out of its model-validation errors. Only the page
  token's refusal carries it, with fieldList naming next-token and its
  own text. maxResults no longer quotes the value.
- Tag calls answer what DSQL answers: 403 for an ARN that is not a
  cluster ARN, 400 BadRequestException for another Region's, 404
  NotFoundException for no cluster. The 403s name the caller.
- Policy versions are epoch milliseconds, DeleteClusterPolicy answers
  the deleted version, and the missing-policy and stale-version errors
  carry DSQL's texts and resourceType.
- Policies are checked and kept as DSQL does: its three refusal texts,
  a service principal, a principal that names no one, a public grant,
  and the lockout check when both policy actions are denied to the
  caller, unless bypassPolicyLockoutSafetyCheck. The kept form is
  Jackson's pretty printer in DSQL's element order, with condition
  operators and keys in HashMap order, as measured.
- The public check shares its condition keys with Lambda web functions
  through PublicAccessConditions, and S3 now takes its fixed-value and
  SourceIp range tests from there. Sharing the whole rule was tried and
  dropped: DSQL was measured to treat some operators otherwise than
  LambdaWeb's and S3's rules do (ForAnyValue:, ArnLike "*",
  StringEquals "*"), so the operator rules stay per service. The
  lockout check is IamPolicyEvaluator's.
- A multi-Region cluster is PENDING_SETUP and lists itself until it and
  each peer name one another, then ACTIVE; its deletion answers
  PENDING_DELETE.
- AWS::DSQL::Cluster reads its properties through CfnPropertyTypes, so
  a PolicyDocument object or DeletionProtectionEnabled "yes" fails as
  on AWS, where Boolean.valueOf made "yes" false. An update leaves a
  property the template no longer sets as it was, deletion protection,
  KMS key and multi-Region alike, and removes only the tags and the
  policy; an earlier change put them back to their defaults, which was
  not measured and is not what CloudFormation does. A policy the
  template does not change keeps its version, and create settles on
  PENDING_SETUP too.

DsqlServiceTest, DsqlClusterPoliciesTest and DsqlCfnProvisionerTest
cover these in isolation, the integration tests over the wire.

* fix(dsql): keep the public access rule to DSQL and forget a deleted policy's version

A review asked to leave S3 and Lambda web functions out of this change,
and pointed at DSQL's own block public access page. The shared helper
is dropped and S3 and Lambda web functions are as on main; folding
their copies into one helper belongs to a separate change.

DSQL now has its own keys: the trusted ones its page lists, and
aws:SourceIp, aws:SourceVpcArn and the three aws:Vpce* keys, which the
page leaves out but DSQL accepts (measured, eu-west-1, 2026-10-20). As
the page says, a policy variable never restricts: StringEquals with
${aws:PrincipalArn}, ${aws:SourceVpc} or a role/${aws:username} ARN is
public on DSQL. ArnEquals reads like ArnLike, as IAM matches both the
same way, so a value that is no ARN, ${aws:SourceArn} among them,
matches nothing and restricts, as measured.

DeleteClusterPolicy left the deleted version on the cluster, so a put
naming it went through; it is now cleared, and a put that names a
version on a cluster with no policy is refused as not found.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-20 15:34:39 -04:00
1 parent 67e4bfec1c
commit 95bf6df474
34 files changed
+3213 -5

No files matched your search

@@ -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) {
@@ -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;
@@ -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");
}
}
@@ -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;
}
}
@@ -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);
}
}
}
@@ -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");
}
}
@@ -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\"}}}]}";
}
}