Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(dsql): evaluate the cluster's resource-based policy on connect (#6319)

Alessandro Lattaof60cf120c672
diff --git a/docs/services/dsql.md b/docs/services/dsql.md
index 853c1b5ebb..2f99370fac 100644
--- a/docs/services/dsql.md
+++ b/docs/services/dsql.md
@@ -84,7 +84,11 @@ When Floci runs in Docker, publish `5432` alongside `4566`.
session, an IAM user's key), its ARN with its path.
- The signature is verified like any other Floci IAM token: the `test` key, or a key or session
Floci issued. With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED`, the principal also needs
- `dsql:DbConnectAdmin` or `dsql:DbConnect` on the cluster ARN.
+ `dsql:DbConnectAdmin` or `dsql:DbConnect` on the cluster ARN, and the cluster's resource-based
+ policy is evaluated as DSQL evaluates it on connect, with the client's address as
+ `aws:SourceIp`. An explicit `Deny` in it refuses the connection with the hint `User: <caller> is
+ not authorized to perform: dsql:<action> on resource: <cluster ARN> with an explicit deny in a
+ resource-based policy`.
- Refusals are `FATAL` with DSQL's text and a `Session Id` detail: `08P01` without TLS, `08006` for
a token refused, `28000` for a role the token cannot sign in as, `55000` for any database other
than `postgres`, and `42704` for a custom (dotted) parameter in the startup.
@@ -186,8 +190,8 @@ it with DSQL's messages:
The policy is kept and returned in DSQL's form: pretty-printed, its elements in DSQL's order, a
list of one value written as that value, condition values as text, an account id as its root ARN,
and `2008-10-17` when it has no `Version`. A policy's version is the time it was set, in epoch
-milliseconds. Cluster policies are not enforced: Floci's IAM enforcement checks a connection's
-identity policies (see [Authentication](#authentication)), and no control plane call.
+milliseconds. With IAM enforcement on, a connection is checked against the cluster's policy (see
+[Authentication](#authentication)); control plane calls are not.
## CloudFormation
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
index 71d83399f5..50c2d20f91 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.dsql;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -10,6 +11,10 @@ import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
/**
* 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.
@@ -17,6 +22,9 @@ import jakarta.inject.Inject;
@ApplicationScoped
public class DsqlPrincipals {
+ /** How IAM ends a refusal that an explicit Deny in the cluster's policy decided. */
+ public static final String EXPLICIT_RESOURCE_DENY = "with an explicit deny in a resource-based policy";
+
private final IamService iamService;
private final RegionResolver regionResolver;
private final Instance<RequestContext> requestContext;
@@ -30,12 +38,36 @@ public class DsqlPrincipals {
}
public CallerArns caller() {
+ return callerOf(accessKeyId());
+ }
+
+ /** Who signs with {@code accessKeyId}, as {@link #caller()} names the caller of a request. */
+ public CallerArns callerOf(String accessKeyId) {
String accountId = regionResolver.getAccountId();
- return iamService.resolveCallerArns(accessKeyId())
+ return iamService.resolveCallerArns(accessKeyId)
.orElseGet(() -> CallerArns.accountRoot(regionResolver.buildGlobalArn("iam", accountId, "root"),
accountId));
}
+ /**
+ * The context a cluster policy is read in for {@code caller}: its principal keys, the global
+ * keys of the cluster in {@code region}, and {@code keys}, such as a connection's
+ * {@code aws:SourceIp}.
+ */
+ public Map<String, List<String>> policyContext(CallerArns caller, String clusterArn, String region,
+ Map<String, List<String>> keys) {
+ Map<String, List<String>> context = new HashMap<>(keys);
+ caller.putPrincipalKeys(context);
+ String accountId = regionResolver.getAccountId();
+ return IamConditionContextResolver.withGlobalContext(context, clusterArn, region, accountId, accountId);
+ }
+
+ /** IAM's refusal of {@code callerArn} for {@code action} on {@code resource}, as DSQL words it. */
+ public static String notAuthorized(String callerArn, String action, String resource, String reason) {
+ return "User: " + callerArn + " is not authorized to perform: " + action + " on resource: " + resource + " "
+ + reason;
+ }
+
/**
* 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.
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlResourcePolicyProvider.java
new file mode 100644
index 0000000000..489837d6c3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlResourcePolicyProvider.java
@@ -0,0 +1,33 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+
+/**
+ * Supplies a DSQL cluster's resource-based policy, when it has one, to IAM policy evaluation, with
+ * the account that owns the cluster: the cluster endpoint evaluates it on connect, as DSQL does
+ * (measured).
+ */
+@ApplicationScoped
+public class DsqlResourcePolicyProvider implements ResourcePolicyProvider {
+
+ private final DsqlService dsqlService;
+
+ @Inject
+ public DsqlResourcePolicyProvider(DsqlService dsqlService) {
+ this.dsqlService = dsqlService;
+ }
+
+ @Override
+ public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
+ return dsqlService.clusterOfArn(resourceArn)
+ .filter(cluster -> cluster.getPolicy() != null)
+ .map(cluster -> List.of(new ResourcePolicy(cluster.getPolicy(),
+ AwsArnUtils.parse(resourceArn).accountId())))
+ .orElse(List.of());
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java
index 7eaa68cac9..e204d422b9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlService.java
@@ -6,7 +6,6 @@ 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;
@@ -28,7 +27,6 @@ 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;
@@ -332,13 +330,9 @@ public class DsqlService implements Resettable {
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;
+ return policyEvaluator.evaluateResourcePolicyFor(List.of(policy), RequestPrincipal.caller(caller), action,
+ clusterArn, principals.policyContext(caller, clusterArn, region, Map.of()))
+ == ResourcePolicyDecision.EXPLICIT_DENY;
}
// ── Tags ──────────────────────────────────────────────────────────────────
@@ -472,7 +466,8 @@ public class DsqlService implements Resettable {
}
}
- private Optional<DsqlCluster> clusterOfArn(String arn) {
+ /** The cluster {@code arn} names in the caller's account, if there is one. */
+ public Optional<DsqlCluster> clusterOfArn(String arn) {
AwsArnUtils.Arn parsed = clusterArnOrNull(arn);
if (parsed == null || !regionResolver.getAccountId().equals(parsed.accountId())) {
return Optional.empty();
@@ -491,15 +486,14 @@ public class DsqlService implements Resettable {
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);
+ + " 'arn:partition:dsql:region:account-id:cluster/cluster-id' and try again."
+ + DsqlPrincipals.notAuthorized(caller, "dsql:" + action, "*",
+ DsqlPrincipals.EXPLICIT_RESOURCE_DENY), 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);
+ throw new AwsException("AccessDeniedException", DsqlPrincipals.notAuthorized(caller, "dsql:" + action, 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);
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java
index e7008fdc74..5215343a59 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java
@@ -6,9 +6,17 @@ import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.services.dsql.DsqlPrincipals;
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.Decision;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
+import io.github.hectorvent.floci.services.iam.RequestPrincipal;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.annotation.PreDestroy;
@@ -53,9 +61,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
* eu-west-1, 2026-10-16): the password is a SigV4 token for the endpoint's host, {@code admin}
* signs {@code DbConnectAdmin} and every other role {@code DbConnect}, a token is taken up to 5
* seconds past its expiry, and a role other than {@code admin} logs in only for an IAM role that
- * {@code AWS IAM GRANT} mapped to it. Every refusal is the same {@code access denied}, with a hint
- * only where DSQL gives one. DSQL lets clients in while a cluster is still CREATING; Floci's
- * clusters are CREATING only while their database starts, and serve once it answers.
+ * {@code AWS IAM GRANT} mapped to it. With IAM enforcement on, the caller's policies and the
+ * cluster's resource-based policy have to let it connect. Every refusal is the same
+ * {@code access denied}, with a hint only where DSQL gives one. DSQL lets clients in while a
+ * cluster is still CREATING; Floci's clusters are CREATING only while their database starts, and
+ * serve once it answers.
*/
@ApplicationScoped
public class DsqlEndpoint {
@@ -71,6 +81,8 @@ public class DsqlEndpoint {
private final IamService iamService;
private final IamPolicyEvaluator policyEvaluator;
private final Instance<ScpProvider> scpProvider;
+ private final Instance<ResourcePolicyProvider> resourcePolicyProviders;
+ private final DsqlPrincipals principals;
private final SigV4RequestValidator validator;
private final boolean enforcement;
private final int configuredPort;
@@ -112,12 +124,15 @@ public class DsqlEndpoint {
@Inject
public DsqlEndpoint(DsqlTlsCertificates certificates, IamService iamService, IamPolicyEvaluator policyEvaluator,
- Instance<ScpProvider> scpProvider, EmulatorConfig config, Clock clock) {
+ Instance<ScpProvider> scpProvider, Instance<ResourcePolicyProvider> resourcePolicyProviders,
+ DsqlPrincipals principals, EmulatorConfig config, Clock clock) {
this.clock = clock;
this.certificates = certificates;
this.iamService = iamService;
this.policyEvaluator = policyEvaluator;
this.scpProvider = scpProvider;
+ this.resourcePolicyProviders = resourcePolicyProviders;
+ this.principals = principals;
this.validator = new SigV4RequestValidator(iamService);
this.enforcement = config.services().iam().enforcementEnabled();
this.configuredPort = config.services().dsql().port();
@@ -275,11 +290,12 @@ public class DsqlEndpoint {
}
/**
- * Whether {@code token} lets {@code user} in, checked in the order DSQL reports: the cluster
- * the client named as its TLS server, the action the user needs, the token's expiry, then its
- * signature and, for a role other than {@code admin}, the IAM role mapped to it.
+ * Whether {@code token} lets {@code user} in from {@code sourceIp}, checked in the order DSQL
+ * reports: the cluster the client named as its TLS server, the action the user needs, the
+ * token's expiry, then its signature, the policies with IAM enforcement on and, for a role other
+ * than {@code admin}, the IAM role mapped to it.
*/
- Admission admit(String token, String user, String serverName) {
+ Admission admit(String token, String user, String serverName, String sourceIp) {
URI uri;
try {
uri = URI.create("https://" + token);
@@ -331,16 +347,16 @@ public class DsqlEndpoint {
}
// The endpoint runs outside any request: the caller's identity and policies are read in the
// cluster's account, as the enforcement filter reads them in the request's.
- String principal = RequestScopes.callAs(route.accountId(), route.region(), () -> {
- if (enforcement && !allowedByIam(accessKeyId, "dsql:" + needed, route)) {
- return null;
- }
- return iamService.resolvePrincipalArn(accessKeyId).orElseGet(() -> AwsArnUtils.Arn.global(
- AwsRegions.partitionFor(route.region()), "iam", route.accountId(), "root").toString());
+ Admission identified = RequestScopes.callAs(route.accountId(), route.region(), () -> {
+ Admission refused = enforcement ? refusedByIam(accessKeyId, "dsql:" + needed, route, sourceIp) : null;
+ return refused != null ? refused : new Admission(true, null, null, route,
+ iamService.resolvePrincipalArn(accessKeyId).orElseGet(() -> AwsArnUtils.Arn.global(
+ AwsRegions.partitionFor(route.region()), "iam", route.accountId(), "root").toString()));
});
- if (principal == null) {
- return Admission.refused(null);
+ if (!identified.allowed()) {
+ return identified;
}
+ String principal = identified.principalArn();
if (!ADMIN.equals(user)) {
try {
if (!mapped(route.backend(), principal, user)) {
@@ -374,22 +390,37 @@ public class DsqlEndpoint {
}
/**
- * Whether the caller's policies let it {@code action} the cluster, under its organization's
- * service control policies as the enforcement filter applies them. A known credential with no
- * policies to evaluate is let through, as the filter lets it.
+ * The refusal DSQL gives unless the caller's policies, under its organization's service control
+ * policies, and the cluster's resource-based policy let it {@code action} the cluster, or null when
+ * they do. DSQL evaluates the cluster's policy on connect, with the client's address as
+ * {@code aws:SourceIp}, and hints only at an explicit Deny in it (measured). A known credential
+ * with no policies to evaluate is let through, as the enforcement filter lets it.
*/
- private boolean allowedByIam(String accessKeyId, String action, Route route) {
+ private Admission refusedByIam(String accessKeyId, String action, Route route, String sourceIp) {
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
if (caller == null) {
- return true;
+ return null;
}
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(route.accountId()) : null;
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
- return policyEvaluator.simulatePrincipalPolicy(caller, action, route.arn(), Map.of())
- == IamPolicyEvaluator.SimulationDecision.ALLOWED;
+ CallerArns arns = principals.callerOf(accessKeyId);
+ List<String> clusterPolicies = ResourcePolicyProviders.policiesFor(resourcePolicyProviders, "dsql",
+ route.arn()).stream().map(ResourcePolicyProvider.ResourcePolicy::policyDocument).toList();
+ Map<String, List<String>> context = principals.policyContext(arns, route.arn(), route.region(),
+ Map.of("aws:SourceIp", List.of(sourceIp)));
+ ResourcePolicyDecision clusterPolicy = policyEvaluator.evaluateResourcePolicyFor(clusterPolicies,
+ RequestPrincipal.caller(arns), action, route.arn(), context);
+ if (policyEvaluator.evaluateResolvedResourcePolicy(caller, clusterPolicy,
+ ResourceAccountRelationship.SAME_ACCOUNT, action, route.arn(), context) == Decision.ALLOW) {
+ return null;
+ }
+ return Admission.refused(clusterPolicy == ResourcePolicyDecision.EXPLICIT_DENY
+ ? DsqlPrincipals.notAuthorized(arns.callerArn(), action, route.arn(),
+ DsqlPrincipals.EXPLICIT_RESOURCE_DENY)
+ : null);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java
index 6c2238a8ef..2fbb2da954 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java
@@ -206,7 +206,8 @@ final class DsqlSession {
return;
}
String token = PostgresWire.cString(password.body(), 0).value();
- DsqlEndpoint.Admission admission = endpoint.admit(token, user, serverName[0]);
+ DsqlEndpoint.Admission admission = endpoint.admit(token, user, serverName[0],
+ socket.getInetAddress().getHostAddress());
if (!admission.allowed()) {
refuse(out, admission.state(), ACCESS_DENIED, admission.hint());
return;
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java
index c4f55cadd8..ba2389a241 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java
@@ -15,6 +15,8 @@ import java.util.Properties;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
@@ -65,6 +67,20 @@ public final class DsqlClusterFixture {
return host;
}
+ public String arn() {
+ return "arn:aws:dsql:" + REGION + ":" + ACCOUNT + ":cluster/" + identifier;
+ }
+
+ /** Gives the cluster {@code policy} through the control plane, as the account's root. */
+ public void putPolicy(String policy) {
+ dsql().body(Map.of("policy", policy)).post("/cluster/" + identifier + "/policy").then().statusCode(200);
+ }
+
+ /** Takes the cluster's policy away, if it has one. */
+ public void removePolicy() {
+ dsql().delete("/cluster/" + identifier + "/policy").then().statusCode(anyOf(is(200), is(404)));
+ }
+
public String url() {
return "jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/postgres";
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicyIntegrationTest.java
new file mode 100644
index 0000000000..4cacfd04be
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterPolicyIntegrationTest.java
@@ -0,0 +1,152 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import com.github.dockerjava.api.DockerClient;
+import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint;
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.postgresql.util.PSQLException;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.time.Instant;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A cluster's resource-based policy on connect, with IAM enforcement on, as Aurora DSQL evaluates it
+ * (measured, eu-west-1, 2026-10-22): an explicit Deny that applies to the caller refuses the
+ * connection, with a hint naming the caller, the action and the cluster, under the conditions the
+ * statement sets; a statement that does not apply leaves the decision to the caller's own policies.
+ */
+@QuarkusTest
+@TestProfile(DsqlEnforcementProfile.class)
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+@Tag("docker")
+class DsqlClusterPolicyIntegrationTest {
+
+ private static final String ACCOUNT = DsqlClusterFixture.ACCOUNT;
+
+ @Inject
+ DockerClient dockerClient;
+
+ @Inject
+ DsqlEndpoint endpoint;
+
+ @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
+ int httpPort;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ private DsqlClusterFixture cluster;
+
+ @BeforeAll
+ void createCluster() {
+ cluster = new DsqlClusterFixture(httpPort, endpoint);
+ cluster.create(dockerClient);
+ }
+
+ @AfterAll
+ void deleteCluster() {
+ cluster.delete();
+ }
+
+ @AfterEach
+ void removePolicy() {
+ cluster.removePolicy();
+ }
+
+ @Test
+ void anExplicitDenyThatAppliesToTheCallerRefusesItsConnection() throws Exception {
+ String userName = "dsql-" + Long.toString(System.nanoTime(), 36);
+ EnforcementFixtures.UserCredentials user = adminUser(userName);
+ String userArn = "arn:aws:iam::" + ACCOUNT + ":user/" + userName;
+ signsIn(user);
+
+ String[] denials = {
+ statement("Deny", "{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}", "dsql:DbConnectAdmin", "*", null),
+ statement("Deny", "\"*\"", "dsql:DbConnectAdmin", "*",
+ "{\"ArnEquals\":{\"aws:PrincipalArn\":\"" + userArn + "\"}}"),
+ statement("Deny", "\"*\"", "dsql:DbConnectAdmin", "*",
+ "{\"IpAddress\":{\"aws:SourceIp\":\"127.0.0.1/32\"}}"),
+ };
+ for (String denial : denials) {
+ cluster.putPolicy(denial);
+ PSQLException refused = assertThrows(PSQLException.class, () -> connect(user).close(), denial);
+ assertEquals("08006", refused.getSQLState(), denial);
+ assertEquals("unable to accept connection, access denied", refused.getServerErrorMessage().getMessage());
+ assertTrue(refused.getServerErrorMessage().getDetail().startsWith("Session Id: "));
+ assertEquals("User: " + userArn + " is not authorized to perform: dsql:DbConnectAdmin on resource: "
+ + cluster.arn() + " with an explicit deny in a resource-based policy",
+ refused.getServerErrorMessage().getHint(), denial);
+ }
+
+ cluster.removePolicy();
+ signsIn(user);
+ }
+
+ @Test
+ void aStatementThatDoesNotApplyLeavesTheCallersOwnPoliciesToDecide() throws Exception {
+ EnforcementFixtures.UserCredentials user = adminUser("dsql-" + Long.toString(System.nanoTime(), 36));
+ String[] others = {
+ statement("Deny", "\"*\"", "dsql:DbConnectAdmin", "*",
+ "{\"IpAddress\":{\"aws:SourceIp\":\"192.0.2.0/24\"}}"),
+ statement("Deny", "{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}", "dsql:DbConnect", "*", null),
+ statement("Deny", "{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}", "dsql:DbConnectAdmin",
+ "arn:aws:dsql:" + DsqlClusterFixture.REGION + ":" + ACCOUNT + ":cluster/abcdefghijklmnopqrstuvwxyz",
+ null),
+ statement("Allow", "{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}", "dsql:DbConnectAdmin", "*",
+ "{\"ArnEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::" + ACCOUNT + ":role/someone-else\"}}"),
+ };
+ for (String other : others) {
+ cluster.putPolicy(other);
+ signsIn(user);
+ }
+ }
+
+ /** A new IAM user whose own policy lets it connect as {@code admin}. */
+ private EnforcementFixtures.UserCredentials adminUser(String userName) {
+ String authorization = EnforcementFixtures.auth(ACCOUNT, "iam");
+ EnforcementFixtures.UserCredentials user = EnforcementFixtures.createUser(cleanup, httpPort, authorization,
+ userName);
+ EnforcementFixtures.putUserPolicy(httpPort, authorization, userName, "connect", """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"dsql:DbConnectAdmin",
+ "Resource":"*"}]}""");
+ return user;
+ }
+
+ private Connection connect(EnforcementFixtures.UserCredentials user) throws Exception {
+ return cluster.connect("admin", cluster.token("DbConnectAdmin", user.accessKeyId(), user.secretAccessKey(),
+ Instant.now(), 900, null));
+ }
+
+ private void signsIn(EnforcementFixtures.UserCredentials user) throws Exception {
+ try (Connection connection = connect(user);
+ Statement statement = connection.createStatement();
+ ResultSet row = statement.executeQuery("SELECT current_user")) {
+ assertTrue(row.next());
+ assertEquals("admin", row.getString(1));
+ }
+ }
+
+ private static String statement(String effect, String principal, String action, String resource,
+ String condition) {
+ return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\",\"Principal\":" + principal
+ + ",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\""
+ + (condition == null ? "" : ",\"Condition\":" + condition) + "}]}";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlEnforcementProfile.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlEnforcementProfile.java
new file mode 100644
index 0000000000..dd30632e63
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlEnforcementProfile.java
@@ -0,0 +1,16 @@
+package io.github.hectorvent.floci.services.dsql;
+
+import io.quarkus.test.junit.QuarkusTestProfile;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** {@link DsqlDatabasesProfile}'s clusters with IAM enforcement on, for what a cluster's policy decides on connect. */
+public final class DsqlEnforcementProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ Map<String, String> overrides = new HashMap<>(new DsqlDatabasesProfile().getConfigOverrides());
+ overrides.put("floci.services.iam.enforcement-enabled", "true");
+ return overrides;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpointTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpointTest.java
index d36eb1c52e..94fea3bbf3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpointTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpointTest.java
@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.dsql.DsqlPrincipals;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.testing.MutableClock;
import jakarta.enterprise.inject.Instance;
@@ -26,8 +28,11 @@ class DsqlEndpointTest {
void createEndpoint() {
@SuppressWarnings("unchecked")
Instance<ScpProvider> scpProvider = mock(Instance.class);
+ @SuppressWarnings("unchecked")
+ Instance<ResourcePolicyProvider> resourcePolicyProviders = mock(Instance.class);
endpoint = new DsqlEndpoint(mock(DsqlTlsCertificates.class), mock(IamService.class),
- mock(IamPolicyEvaluator.class), scpProvider, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), clock);
+ mock(IamPolicyEvaluator.class), scpProvider, resourcePolicyProviders, mock(DsqlPrincipals.class),
+ mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), clock);
}
@AfterEach