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

@@ -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();
@@ -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,
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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();
}
}
@@ -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));
}
}
@@ -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;
}
}
}
@@ -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) {
}
}
@@ -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);
}
}
@@ -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; }
}