values = new ArrayList<>();
+ array.forEach(item -> values.add(item.asText()));
+ return values;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java
new file mode 100644
index 0000000000..6ba78b8760
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicies.java
@@ -0,0 +1,370 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.util.DefaultIndenter;
+import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+
+/**
+ * A cluster's resource policy as DSQL reads and keeps it (measured, eu-west-1, 2026-10-20).
+ *
+ * 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 DOCUMENT_KEYS = Set.of("Version", "Id", "Statement");
+ private static final Set STATEMENT_KEYS = Set.of(
+ "Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");
+ private static final Set 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 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 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 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 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 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 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 kept = new HashMap<>();
+ Iterator> types = principal.fields();
+ while (types.hasNext()) {
+ Map.Entry type = types.next();
+ switch (type.getKey()) {
+ case "AWS" -> {
+ List 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> operators = new HashMap<>();
+ Iterator> each = condition.fields();
+ while (each.hasNext()) {
+ Map.Entry 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 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> operators = condition.fields();
+ while (operators.hasNext()) {
+ Map.Entry operator = operators.next();
+ String name = operator.getKey();
+ if (name.startsWith("ForAnyValue:")) {
+ name = name.substring("ForAnyValue:".length());
+ }
+ Iterator> keys = operator.getValue().fields();
+ while (keys.hasNext()) {
+ Map.Entry 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 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 values) {
+ if (values.size() == 1) {
+ return mapper.getNodeFactory().textNode(values.getFirst());
+ }
+ ArrayNode list = mapper.createArrayNode();
+ values.forEach(list::add);
+ return list;
+ }
+
+ private static List texts(JsonNode node) {
+ List 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 fieldNames(JsonNode node) {
+ Set names = new HashSet<>();
+ node.fieldNames().forEachRemaining(names::add);
+ return names;
+ }
+
+ private static Set lowercase(Set keys) {
+ Set lowered = new HashSet<>();
+ keys.forEach(key -> lowered.add(key.toLowerCase(Locale.ROOT)));
+ return Set.copyOf(lowered);
+ }
+
+ private static AwsException refused(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java
new file mode 100644
index 0000000000..a365bfa35b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlController.java
@@ -0,0 +1,292 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Aurora DSQL's REST-JSON control plane: {@code /cluster}, {@code /cluster/{identifier}} and its
+ * policy, and {@code /clusters/{identifier}/vpc-endpoint-service-name}, as the service model
+ * (2018-05-10) defines them. Tags go through the shared {@code /tags/{resourceArn}} dispatcher.
+ */
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class DsqlController {
+
+ private static final int MAX_POLICY_LENGTH = 20480;
+
+ private final DsqlService service;
+ private final RegionResolver regionResolver;
+
+ @Inject
+ public DsqlController(DsqlService service, RegionResolver regionResolver) {
+ this.service = service;
+ this.regionResolver = regionResolver;
+ }
+
+ @POST
+ @Path("/cluster")
+ public Response createCluster(@Context HttpHeaders headers, Map body) {
+ Map request = body == null ? Map.of() : body;
+ Map 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 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