Light, fluffy, and always free - The AWS Local Emulator alternative
feat(rds): IAM role associations for DB clusters and instances (#5367)
David5e48cbb80b77
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.javaindex 8e03485b36..7d4dc055bd 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java@@ -18,15 +18,22 @@ import software.amazon.awssdk.services.rds.model.CreateDbProxyResponse;import software.amazon.awssdk.services.rds.model.CreateDbSubnetGroupResponse;import software.amazon.awssdk.services.rds.model.CreateOptionGroupResponse;import software.amazon.awssdk.services.rds.model.DBCluster;+import software.amazon.awssdk.services.rds.model.DBClusterAssociatedRole;import software.amazon.awssdk.services.rds.model.DBClusterEndpoint;+import software.amazon.awssdk.services.rds.model.DBClusterRole;import software.amazon.awssdk.services.rds.model.DBClusterSnapshot;import software.amazon.awssdk.services.rds.model.DBEngineVersion;import software.amazon.awssdk.services.rds.model.DBInstance;+import software.amazon.awssdk.services.rds.model.DBInstanceRole;import software.amazon.awssdk.services.rds.model.DBProxyTarget;import software.amazon.awssdk.services.rds.model.DBSnapshot;import software.amazon.awssdk.services.rds.model.DbClusterEndpointAlreadyExistsException;import software.amazon.awssdk.services.rds.model.DbClusterEndpointNotFoundException;+import software.amazon.awssdk.services.rds.model.DbClusterRoleAlreadyExistsException;+import software.amazon.awssdk.services.rds.model.DbClusterRoleNotFoundException;import software.amazon.awssdk.services.rds.model.DbClusterSnapshotNotFoundException;+import software.amazon.awssdk.services.rds.model.DbInstanceRoleAlreadyExistsException;+import software.amazon.awssdk.services.rds.model.DbInstanceRoleNotFoundException;import software.amazon.awssdk.services.rds.model.DbSnapshotAlreadyExistsException;import software.amazon.awssdk.services.rds.model.DbSnapshotNotFoundException;import software.amazon.awssdk.services.rds.model.DescribeDbProxiesResponse;@@ -757,6 +764,62 @@ class RdsControlPlaneTest {}}+ @Test+ @DisplayName("IAM role associations: add, describe and remove for a cluster and an instance")+ void sdkRoundTripsIamRoleAssociations() {+ String clusterName = TestFixtures.uniqueName("rds-roles-cluster");+ String instanceName = TestFixtures.uniqueName("rds-roles-db");+ String s3Role = "arn:aws:iam::000000000000:role/rds-s3-import";+ String lambdaRole = "arn:aws:iam::000000000000:role/rds-lambda";+ try {+ CreateDbClusterResponse created = rds.createDBCluster(b -> b+ .dbClusterIdentifier(clusterName)+ .engine("aurora-postgresql")+ .engineVersion("16.3")+ .masterUsername("admin")+ .masterUserPassword("roles-secret")+ .associatedRoles(DBClusterAssociatedRole.builder().roleArn(s3Role).featureName("s3Import").build()));+ assertThat(created.dbCluster().associatedRoles())+ .extracting(DBClusterRole::roleArn, DBClusterRole::featureName, DBClusterRole::status)+ .containsExactly(tuple(s3Role, "s3Import", "ACTIVE"));++ rds.addRoleToDBCluster(b -> b.dbClusterIdentifier(clusterName).roleArn(lambdaRole));+ assertThat(rds.describeDBClusters(b -> b.dbClusterIdentifier(clusterName))+ .dbClusters().get(0).associatedRoles())+ .extracting(DBClusterRole::roleArn)+ .containsExactly(s3Role, lambdaRole);+ assertThatThrownBy(() -> rds.addRoleToDBCluster(b -> b.dbClusterIdentifier(clusterName).roleArn(s3Role)))+ .isInstanceOf(DbClusterRoleAlreadyExistsException.class);++ rds.removeRoleFromDBCluster(b -> b.dbClusterIdentifier(clusterName).roleArn(s3Role));+ assertThatThrownBy(() -> rds.removeRoleFromDBCluster(b -> b+ .dbClusterIdentifier(clusterName).roleArn(s3Role)))+ .isInstanceOf(DbClusterRoleNotFoundException.class);++ createDbInstance(rds, instanceName, "roles-secret");+ rds.addRoleToDBInstance(b -> b.dbInstanceIdentifier(instanceName).roleArn(s3Role).featureName("s3Import"));+ assertThat(rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName))+ .dbInstances().get(0).associatedRoles())+ .extracting(DBInstanceRole::roleArn, DBInstanceRole::featureName, DBInstanceRole::status)+ .containsExactly(tuple(s3Role, "s3Import", "ACTIVE"));+ assertThatThrownBy(() -> rds.addRoleToDBInstance(b -> b+ .dbInstanceIdentifier(instanceName).roleArn(lambdaRole).featureName("s3Import")))+ .isInstanceOf(DbInstanceRoleAlreadyExistsException.class);++ rds.removeRoleFromDBInstance(b -> b.dbInstanceIdentifier(instanceName).roleArn(s3Role).featureName("s3Import"));+ assertThatThrownBy(() -> rds.removeRoleFromDBInstance(b -> b+ .dbInstanceIdentifier(instanceName).roleArn(s3Role).featureName("s3Import")))+ .isInstanceOf(DbInstanceRoleNotFoundException.class);+ } finally {+ deleteDbInstance(rds, instanceName);+ try {+ rds.deleteDBCluster(b -> b.dbClusterIdentifier(clusterName).skipFinalSnapshot(true));+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Failed to clean up RDS cluster " + clusterName, e);+ }+ }+ }+@Test@DisplayName("Catalogue reads: engine versions, engine defaults and valid instance modifications")void sdkReadsTheEngineCatalogue() {diff --git a/docs/services/index.md b/docs/services/index.mdindex 910f22a12d..7847d23828 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -62,7 +62,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 || [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 30 || [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |-| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 94 |+| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 98 || [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 || [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 || [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 |diff --git a/docs/services/rds.md b/docs/services/rds.mdindex f0dd22bdfe..2d824b98c9 100644--- a/docs/services/rds.md+++ b/docs/services/rds.md@@ -71,6 +71,10 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou| `DescribeDBClusterEndpoints` | List a cluster's built-in writer and reader endpoints and its custom endpoints, with the four documented filters || `ModifyDBClusterEndpoint` | Change a custom endpoint's type or member list || `DeleteDBClusterEndpoint` | Delete a custom endpoint |+| `AddRoleToDBCluster` | Associate an IAM role with a cluster, optionally for a feature; see [IAM role associations](#iam-role-associations) |+| `RemoveRoleFromDBCluster` | Remove a role from a cluster |+| `AddRoleToDBInstance` | Associate an IAM role with an instance for a feature |+| `RemoveRoleFromDBInstance` | Remove a role from an instance || `AddSourceIdentifierToSubscription` | Add a source id to a subscription || `RemoveSourceIdentifierFromSubscription` | Remove a source id from a subscription || `CreateDBSubnetGroup` | Create a DB subnet group; tags given here are readable through `ListTagsForResource` |@@ -612,6 +616,29 @@ Custom endpoints are modelled, not routed: a custom endpoint reports the clusterreachable, but connections through it go where the cluster endpoint sends them rather than beingspread across the chosen members.+## IAM role associations++`AddRoleToDBCluster` and `AddRoleToDBInstance` associate an IAM role with an available cluster or+instance, and `DescribeDBClusters` / `DescribeDBInstances` report it in `AssociatedRoles` with status+`ACTIVE` straight away. `CreateDBCluster` accepts `AssociatedRoles` too: a list that names a role twice,+or has an entry without a `RoleArn`, refuses the create before any cluster exists, and the roles are+associated in one step, so a create that fails leaves no cluster behind.++`FeatureName` (such as `s3Import`, `s3Export` or `Lambda`) is optional for a cluster and required for an+instance. A role is associated at most once per cluster (`DBClusterRoleAlreadyExists`, which covers+the role ARN only, so two roles may share a feature), and a role or a feature at most once per instance+(`DBInstanceRoleAlreadyExists`, documented as "The specified RoleArn or FeatureName value is already+associated"). `RemoveRoleFromDBCluster` removes the+role, matching the feature name when one is given, and `RemoveRoleFromDBInstance` removes the role for+the feature named; an association that does not exist is `DBClusterRoleNotFound` /+`DBInstanceRoleNotFound`. A stopped cluster or instance refuses both (`InvalidDBClusterStateFault` /+`InvalidDBInstanceState`).++Associations are recorded, not exercised: Floci does not check the role in IAM, does not check the+feature name against the engine, and does not hand the role's credentials to the database, so an+`aws_s3` import still needs credentials of its own. Deleting a cluster or instance drops its+associations, and snapshots, restores and read replicas start without any.+## Aurora managed password opt-outWhen `ModifyDBCluster` disables `ManageMasterUserPassword` while the managed secret hasdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.javaindex ab539de565..fd9402462e 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java@@ -560,7 +560,7 @@ public class AwsQueryController {"CreateDBSubnetGroup", "DescribeDBSubnetGroups", "ModifyDBSubnetGroup", "DeleteDBSubnetGroup","AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource","CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",- "AddRoleToDBCluster", "RemoveRoleFromDBCluster",+ "AddRoleToDBCluster", "RemoveRoleFromDBCluster", "AddRoleToDBInstance", "RemoveRoleFromDBInstance","DescribeGlobalClusters","CreateDBParameterGroup", "DescribeDBParameterGroups","DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters",diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.javaindex 8024531f9f..f0ae904fab 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.rds.model.DbProxy;import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;+import io.github.hectorvent.floci.services.rds.model.DbRoleAssociation;import io.github.hectorvent.floci.services.rds.model.DbSnapshot;import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;import io.github.hectorvent.floci.services.rds.model.EventSubscription;@@ -46,7 +47,11 @@ import java.util.Collection;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.SortedSet;+import java.util.TreeSet;import java.util.function.BiFunction;+import java.util.regex.Matcher;+import java.util.regex.Pattern;/*** Query-protocol handler for all RDS actions (form-encoded POST, XML response).@@ -108,6 +113,10 @@ public class RdsQueryHandler {case "DescribeDBClusterEndpoints" -> handleDescribeDbClusterEndpoints(params, region);case "ModifyDBClusterEndpoint" -> handleModifyDbClusterEndpoint(params, region);case "DeleteDBClusterEndpoint" -> handleDeleteDbClusterEndpoint(params, region);+ case "AddRoleToDBCluster" -> handleAddRoleToDbCluster(params, region);+ case "RemoveRoleFromDBCluster" -> handleRemoveRoleFromDbCluster(params, region);+ case "AddRoleToDBInstance" -> handleAddRoleToDbInstance(params, region);+ case "RemoveRoleFromDBInstance" -> handleRemoveRoleFromDbInstance(params, region);case "AddSourceIdentifierToSubscription" ->handleAddSourceIdentifierToSubscription(params, region);case "RemoveSourceIdentifierFromSubscription" ->@@ -359,6 +368,57 @@ public class RdsQueryHandler {new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build();}+ private Response handleAddRoleToDbCluster(MultivaluedMap<String, String> params, String region) {+ service.addRoleToDbCluster(region, params.getFirst("DBClusterIdentifier"),+ params.getFirst("RoleArn"), params.getFirst("FeatureName"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("AddRoleToDBCluster", AwsNamespaces.RDS)).build();+ }++ private Response handleRemoveRoleFromDbCluster(MultivaluedMap<String, String> params, String region) {+ service.removeRoleFromDbCluster(region, params.getFirst("DBClusterIdentifier"),+ params.getFirst("RoleArn"), params.getFirst("FeatureName"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("RemoveRoleFromDBCluster", AwsNamespaces.RDS)).build();+ }++ private Response handleAddRoleToDbInstance(MultivaluedMap<String, String> params, String region) {+ service.addRoleToDbInstance(region, params.getFirst("DBInstanceIdentifier"),+ params.getFirst("RoleArn"), params.getFirst("FeatureName"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("AddRoleToDBInstance", AwsNamespaces.RDS)).build();+ }++ private Response handleRemoveRoleFromDbInstance(MultivaluedMap<String, String> params, String region) {+ service.removeRoleFromDbInstance(region, params.getFirst("DBInstanceIdentifier"),+ params.getFirst("RoleArn"), params.getFirst("FeatureName"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("RemoveRoleFromDBInstance", AwsNamespaces.RDS)).build();+ }++ /**+ * The {@code AssociatedRoles} a {@code CreateDBCluster} request names. botocore and the Java SDK+ * send the model's member name ({@code AssociatedRoles.DBClusterAssociatedRole.N.RoleArn});+ * {@code .member.N} is read too, as the other RDS lists accept it.+ */+ private static List<DbRoleAssociation> parseAssociatedRoles(MultivaluedMap<String, String> params) {+ List<DbRoleAssociation> roles = new ArrayList<>();+ for (String prefix : List.of("AssociatedRoles.DBClusterAssociatedRole", "AssociatedRoles.member")) {+ // Every index the request names, in order, whichever field it carries: an entry with a+ // FeatureName and no RoleArn reaches validation and is refused there, and a gap in the+ // numbering does not hide the entries after it.+ Pattern field = Pattern.compile(Pattern.quote(prefix) + "\\.(\\d+)\\.(RoleArn|FeatureName)");+ SortedSet<Integer> indexes = new TreeSet<>();+ for (String key : params.keySet()) {+ Matcher matcher = field.matcher(key);+ if (matcher.matches()) {+ indexes.add(Integer.parseInt(matcher.group(1)));+ }+ }+ for (int i : indexes) {+ roles.add(new DbRoleAssociation(params.getFirst(prefix + "." + i + ".RoleArn"),+ params.getFirst(prefix + "." + i + ".FeatureName")));+ }+ }+ return roles;+ }+private Response handleCreateDbClusterEndpoint(MultivaluedMap<String, String> params, String region) {DbClusterEndpoint endpoint = service.createDbClusterEndpoint(region,params.getFirst("DBClusterIdentifier"),@@ -1115,6 +1175,8 @@ public class RdsQueryHandler {}try {+ List<DbRoleAssociation> associatedRoles = parseAssociatedRoles(params);+ service.validateClusterRoleAssociations(id, associatedRoles);Double serverlessV2Min = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MinCapacity");Double serverlessV2Max = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MaxCapacity");Integer serverlessV2SecondsUntilAutoPause = parseIntegerParam(@@ -1149,6 +1211,14 @@ public class RdsQueryHandler {manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted,requestedPort);}+ if (!associatedRoles.isEmpty()) {+ try {+ cluster = service.addRolesToNewDbCluster(region, id, associatedRoles);+ } catch (AwsException e) {+ service.deleteDbCluster(id, region);+ throw e;+ }+ }String result = dbClusterXml(cluster);return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, result)).build();} catch (AwsException e) {@@ -2685,6 +2755,7 @@ public class RdsQueryHandler {xml.elem("DBClusterIdentifier", i.getDbClusterIdentifier());}xml.raw(readReplicaXml(i));+ writeAssociatedRoles(xml, i.getAssociatedRoles(), "DBInstanceRole");xml.start("TagList");writeTags(xml, i.getTags());xml.end("TagList");@@ -2894,9 +2965,23 @@ public class RdsQueryHandler {}}xml.end("DBClusterMembers");+ writeAssociatedRoles(xml, c.getAssociatedRoles(), "DBClusterRole");return xml.build();}+ /** {@code AssociatedRoles}, each entry named as the model names it for the resource. */+ private static void writeAssociatedRoles(XmlBuilder xml, List<DbRoleAssociation> roles, String elementName) {+ xml.start("AssociatedRoles");+ for (DbRoleAssociation role : roles) {+ xml.start(elementName).elem("RoleArn", role.getRoleArn());+ if (role.getFeatureName() != null) {+ xml.elem("FeatureName", role.getFeatureName());+ }+ xml.elem("Status", role.getStatus()).end(elementName);+ }+ xml.end("AssociatedRoles");+ }+private String paramGroupXml(DbParameterGroup g) {return new XmlBuilder().start("DBParameterGroup").raw(paramGroupInnerXml(g)).end("DBParameterGroup").build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.javaindex cad1249c18..33d399156c 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java@@ -49,6 +49,7 @@ import io.github.hectorvent.floci.services.rds.model.DbProxy;import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;+import io.github.hectorvent.floci.services.rds.model.DbRoleAssociation;import io.github.hectorvent.floci.services.rds.model.DbSnapshot;import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;import io.github.hectorvent.floci.services.rds.model.EventSubscription;@@ -75,6 +76,7 @@ import java.util.ArrayList;import java.util.Collection;import java.util.Comparator;import java.util.HashMap;+import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;@@ -9556,6 +9558,166 @@ public class RdsService implements Resettable, ResourceProvider {return subscription;}+ // ── IAM role associations ─────────────────────────────────────────────────++ /**+ * Associates an IAM role with a DB cluster. A cluster names each role once, so the same role+ * twice is refused ({@code DBClusterRoleAlreadyExists} covers the role ARN only). The role is+ * {@code ACTIVE} at once and is not looked up in IAM.+ */+ public synchronized DbCluster addRoleToDbCluster(String region, String clusterId, String roleArn,+ String featureName) {+ requireParameter(clusterId, "DBClusterIdentifier");+ requireParameter(roleArn, "RoleArn");+ String effectiveRegion = effectiveRegion(region);+ DbCluster cluster = getDbCluster(clusterId, effectiveRegion);+ requireAvailableCluster(cluster, clusterId);+ requireRoleNotAssociated(cluster, clusterId, roleArn);+ cluster.getAssociatedRoles().add(new DbRoleAssociation(roleArn, blankToNull(featureName)));+ putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);+ LOG.infov("Role {0} associated with DB cluster {1}", roleArn, clusterId);+ return RESPONSE_COPIER.convertValue(cluster, DbCluster.class);+ }++ /**+ * Gives a cluster {@code CreateDBCluster} just made the roles the request named, all in one+ * step: either every role is associated or none is. The handler deletes the new cluster when+ * this refuses, so a failed create leaves nothing behind.+ */+ public synchronized DbCluster addRolesToNewDbCluster(String region, String clusterId,+ List<DbRoleAssociation> roles) {+ String effectiveRegion = effectiveRegion(region);+ DbCluster cluster = getDbCluster(clusterId, effectiveRegion);+ requireAvailableCluster(cluster, clusterId);+ for (DbRoleAssociation role : roles) {+ requireRoleNotAssociated(cluster, clusterId, role.getRoleArn());+ }+ for (DbRoleAssociation role : roles) {+ cluster.getAssociatedRoles().add(new DbRoleAssociation(role.getRoleArn(),+ blankToNull(role.getFeatureName())));+ }+ putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);+ return RESPONSE_COPIER.convertValue(cluster, DbCluster.class);+ }++ private static void requireRoleNotAssociated(DbCluster cluster, String clusterId, String roleArn) {+ for (DbRoleAssociation existing : cluster.getAssociatedRoles()) {+ if (existing.getRoleArn().equals(roleArn)) {+ throw new AwsException("DBClusterRoleAlreadyExists", "Role ARN " + roleArn+ + " is already associated with DB cluster " + clusterId + ".", 400);+ }+ }+ }++ /**+ * Removes a role from a DB cluster. When a feature name is given, the role must be associated+ * for that feature.+ */+ public synchronized DbCluster removeRoleFromDbCluster(String region, String clusterId, String roleArn,+ String featureName) {+ requireParameter(clusterId, "DBClusterIdentifier");+ requireParameter(roleArn, "RoleArn");+ String effectiveRegion = effectiveRegion(region);+ DbCluster cluster = getDbCluster(clusterId, effectiveRegion);+ requireAvailableCluster(cluster, clusterId);+ String feature = blankToNull(featureName);+ boolean removed = cluster.getAssociatedRoles().removeIf(existing -> existing.getRoleArn().equals(roleArn)+ && (feature == null || feature.equals(existing.getFeatureName())));+ if (!removed) {+ throw new AwsException("DBClusterRoleNotFound", "Role ARN " + roleArn+ + (feature == null ? "" : " for feature " + feature)+ + " is not associated with DB cluster " + clusterId + ".", 404);+ }+ putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);+ LOG.infov("Role {0} disassociated from DB cluster {1}", roleArn, clusterId);+ return RESPONSE_COPIER.convertValue(cluster, DbCluster.class);+ }++ /**+ * Associates an IAM role with a DB instance for one feature. The role and the feature are each+ * associated at most once, so either one already present is refused.+ */+ public synchronized DbInstance addRoleToDbInstance(String region, String instanceId, String roleArn,+ String featureName) {+ requireParameter(instanceId, "DBInstanceIdentifier");+ requireParameter(roleArn, "RoleArn");+ requireParameter(featureName, "FeatureName");+ String effectiveRegion = effectiveRegion(region);+ DbInstance instance = getDbInstance(instanceId, effectiveRegion);+ requireAvailableInstance(instance, instanceId);+ for (DbRoleAssociation existing : instance.getAssociatedRoles()) {+ if (existing.getRoleArn().equals(roleArn) || featureName.equals(existing.getFeatureName())) {+ throw new AwsException("DBInstanceRoleAlreadyExists", "Role ARN " + existing.getRoleArn()+ + " is already associated with DB instance " + instanceId + " for feature "+ + existing.getFeatureName() + ".", 400);+ }+ }+ instance.getAssociatedRoles().add(new DbRoleAssociation(roleArn, featureName));+ putInstanceForScope(currentAccountId(), effectiveRegion, instanceId, instance);+ LOG.infov("Role {0} associated with DB instance {1} for feature {2}", roleArn, instanceId, featureName);+ return RESPONSE_COPIER.convertValue(instance, DbInstance.class);+ }++ /** Removes a role from a DB instance; the role must be associated for the feature named. */+ public synchronized DbInstance removeRoleFromDbInstance(String region, String instanceId, String roleArn,+ String featureName) {+ requireParameter(instanceId, "DBInstanceIdentifier");+ requireParameter(roleArn, "RoleArn");+ requireParameter(featureName, "FeatureName");+ String effectiveRegion = effectiveRegion(region);+ DbInstance instance = getDbInstance(instanceId, effectiveRegion);+ requireAvailableInstance(instance, instanceId);+ boolean removed = instance.getAssociatedRoles().removeIf(existing -> existing.getRoleArn().equals(roleArn)+ && featureName.equals(existing.getFeatureName()));+ if (!removed) {+ throw new AwsException("DBInstanceRoleNotFound", "Role ARN " + roleArn+ + " is not associated with DB instance " + instanceId + " for feature " + featureName + ".", 404);+ }+ putInstanceForScope(currentAccountId(), effectiveRegion, instanceId, instance);+ LOG.infov("Role {0} disassociated from DB instance {1}", roleArn, instanceId);+ return RESPONSE_COPIER.convertValue(instance, DbInstance.class);+ }++ /**+ * Checks the roles a {@code CreateDBCluster} request names before the cluster exists, by the+ * rules {@link #addRoleToDbCluster} applies one at a time, so a list that would be refused part+ * way through refuses the create instead of leaving a cluster with half its roles.+ */+ public void validateClusterRoleAssociations(String clusterId, List<DbRoleAssociation> roles) {+ Set<String> roleArns = new HashSet<>();+ for (DbRoleAssociation role : roles) {+ requireParameter(role.getRoleArn(), "AssociatedRoles.RoleArn");+ if (!roleArns.add(role.getRoleArn())) {+ throw new AwsException("DBClusterRoleAlreadyExists", "Role ARN " + role.getRoleArn()+ + " is named more than once for DB cluster " + clusterId + ".", 400);+ }+ }+ }++ private static String blankToNull(String value) {+ return isBlank(value) ? null : value;+ }++ private static void requireParameter(String value, String name) {+ if (isBlank(value)) {+ throw new AwsException("MissingParameter", "The request must contain the parameter " + name + ".", 400);+ }+ }++ private static void requireAvailableCluster(DbCluster cluster, String clusterId) {+ if (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE) {+ throw new AwsException("InvalidDBClusterStateFault",+ "DB cluster " + clusterId + " is not in available state.", 400);+ }+ }++ private static void requireAvailableInstance(DbInstance instance, String instanceId) {+ if (instance.getStatus() != null && instance.getStatus() != DbInstanceStatus.AVAILABLE) {+ throw new AwsException("InvalidDBInstanceState",+ "DB instance " + instanceId + " is not in available state.", 400);+ }+ }+// ── Cluster endpoints ─────────────────────────────────────────────────────private static final int MAX_CUSTOM_ENDPOINTS_PER_CLUSTER = 5;diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.javaindex 0dac695e07..f6715cfd2a 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java@@ -42,6 +42,7 @@ public class DbCluster {private Instant createdAt;private int proxyPort;private Map<String, String> tags = new LinkedHashMap<>();+ private List<DbRoleAssociation> associatedRoles = new ArrayList<>();private String engineMode;private boolean storageEncrypted;@@ -179,6 +180,11 @@ public class DbCluster {public int getProxyPort() { return proxyPort; }public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }+ public List<DbRoleAssociation> getAssociatedRoles() { return associatedRoles; }+ public void setAssociatedRoles(List<DbRoleAssociation> associatedRoles) {+ this.associatedRoles = associatedRoles != null ? new ArrayList<>(associatedRoles) : new ArrayList<>();+ }+public Map<String, String> getTags() { return tags; }public void setTags(Map<String, String> tags) { this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); }diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.javaindex 11ab18fd7f..c626993c75 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java@@ -67,6 +67,7 @@ public class DbInstance {private String masterUserSecretStatus;private String masterUserSecretKmsKeyId;private Map<String, String> tags = new LinkedHashMap<>();+ private List<DbRoleAssociation> associatedRoles = new ArrayList<>();private Instant createdAt;private int proxyPort;// Read replication links, kept on both ends the way DescribeDBInstances reports them: a@@ -246,6 +247,11 @@ public class DbInstance {&& !readReplicaSourceDbInstanceIdentifier.isBlank();}+ public List<DbRoleAssociation> getAssociatedRoles() { return associatedRoles; }+ public void setAssociatedRoles(List<DbRoleAssociation> associatedRoles) {+ this.associatedRoles = associatedRoles != null ? new ArrayList<>(associatedRoles) : new ArrayList<>();+ }+public Map<String, String> getTags() { return tags; }public void setTags(Map<String, String> tags) { this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); }diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbRoleAssociation.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbRoleAssociation.javanew file mode 100644index 0000000000..cd850d35e4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbRoleAssociation.java@@ -0,0 +1,35 @@+package io.github.hectorvent.floci.services.rds.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * An IAM role associated with a DB cluster or DB instance, reported as a {@code DBClusterRole} or+ * {@code DBInstanceRole} in {@code AssociatedRoles}. The feature name is optional for a cluster+ * and required for an instance. The status is {@code ACTIVE} from the moment the role is added.+ */+@RegisterForReflection+public class DbRoleAssociation {++ public static final String ACTIVE = "ACTIVE";++ private String roleArn;+ private String featureName;+ private String status;++ public DbRoleAssociation() {}++ public DbRoleAssociation(String roleArn, String featureName) {+ this.roleArn = roleArn;+ this.featureName = featureName;+ this.status = ACTIVE;+ }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }++ public String getFeatureName() { return featureName; }+ public void setFeatureName(String featureName) { this.featureName = featureName; }++ public String getStatus() { return status; }+ public void setStatus(String status) { this.status = status; }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.javaindex 84d3187565..202620e4a1 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java@@ -732,6 +732,29 @@ class RdsQueryHandlerTest {assertFalse(body.contains("<MasterUserSecret>"));}+ @Test+ void createDbClusterDeletesTheClusterWhenItsRolesAreRefused() {+ DbCluster cluster = makeCluster("mycluster");+ when(service.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),+ any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(),+ any(), anyBoolean()))+ .thenReturn(cluster);+ // Another request associated the role between the create and the roles being added.+ when(service.addRolesToNewDbCluster(any(), eq("mycluster"), anyList()))+ .thenThrow(new AwsException("DBClusterRoleAlreadyExists", "already associated", 400));++ MultivaluedMap<String, String> p = params();+ p.add("DBClusterIdentifier", "mycluster");+ p.add("Engine", "aurora-postgresql");+ p.add("MasterUsername", "admin");+ p.add("AssociatedRoles.DBClusterAssociatedRole.1.RoleArn", "arn:aws:iam::000000000000:role/s3");+ Response response = handler.handle("CreateDBCluster", p);++ assertEquals(400, response.getStatus());+ assertTrue(((String) response.getEntity()).contains("<Code>DBClusterRoleAlreadyExists</Code>"));+ verify(service).deleteDbCluster(eq("mycluster"), any());+ }+@Testvoid modifyDbClusterPassesManagedMasterUserSecretOptions() {DbCluster cluster = makeCluster("mycluster");diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsRoleAssociationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsRoleAssociationIntegrationTest.javanew file mode 100644index 0000000000..5d0e9cdc17--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsRoleAssociationIntegrationTest.java@@ -0,0 +1,272 @@+package io.github.hectorvent.floci.services.rds;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static io.restassured.http.ContentType.URLENC;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.not;++/**+ * IAM role associations over the Query protocol: add and remove for DB clusters and DB instances,+ * the {@code AssociatedRoles} the describe calls return, {@code CreateDBCluster}'s own+ * {@code AssociatedRoles}, and the API reference's errors.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class RdsRoleAssociationIntegrationTest {++ private static final String CLUSTER = "roles-cluster";+ private static final String INSTANCE = "roles-instance";+ private static final String S3_ROLE = "arn:aws:iam::000000000000:role/rds-s3";+ private static final String LAMBDA_ROLE = "arn:aws:iam::000000000000:role/rds-lambda";+ private static final String CLUSTER_ROLES =+ "DescribeDBClustersResponse.DescribeDBClustersResult.DBClusters.DBCluster.AssociatedRoles.DBClusterRole";+ private static final String INSTANCE_ROLES =+ "DescribeDBInstancesResponse.DescribeDBInstancesResult.DBInstances.DBInstance.AssociatedRoles.DBInstanceRole";++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20261009/us-east-1/rds/aws4_request, "+ + "SignedHeaders=content-type;host, Signature=test";++ private static RequestSpecification query(String action) {+ return given().header("Authorization", AUTH)+ .contentType(URLENC)+ .formParam("Action", action)+ .formParam("Version", "2014-10-31");+ }++ private static RequestSpecification clusterRole(String action, String roleArn) {+ return query(action).formParam("DBClusterIdentifier", CLUSTER).formParam("RoleArn", roleArn);+ }++ private static RequestSpecification instanceRole(String action, String roleArn, String feature) {+ return query(action).formParam("DBInstanceIdentifier", INSTANCE)+ .formParam("RoleArn", roleArn).formParam("FeatureName", feature);+ }++ @Test+ @Order(1)+ void createsTheResources() {+ query("CreateDBCluster")+ .formParam("DBClusterIdentifier", CLUSTER)+ .formParam("Engine", "aurora-postgresql")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .when().post("/").then().statusCode(200)+ .body(containsString("<AssociatedRoles></AssociatedRoles>"));+ query("CreateDBInstance")+ .formParam("DBInstanceIdentifier", INSTANCE)+ .formParam("Engine", "postgres")+ .formParam("DBInstanceClass", "db.t3.micro")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .formParam("AllocatedStorage", "20")+ .when().post("/").then().statusCode(200);+ }++ @Test+ @Order(2)+ void addsRolesToAClusterAndDescribesThem() {+ clusterRole("AddRoleToDBCluster", S3_ROLE).formParam("FeatureName", "s3Import")+ .when().post("/").then().statusCode(200)+ .body(containsString("<AddRoleToDBClusterResponse"));+ // The feature name is optional for a cluster.+ clusterRole("AddRoleToDBCluster", LAMBDA_ROLE)+ .when().post("/").then().statusCode(200);++ query("DescribeDBClusters").formParam("DBClusterIdentifier", CLUSTER)+ .when().post("/").then().statusCode(200)+ .body(CLUSTER_ROLES + "[0].RoleArn", equalTo(S3_ROLE))+ .body(CLUSTER_ROLES + "[0].FeatureName", equalTo("s3Import"))+ .body(CLUSTER_ROLES + "[0].Status", equalTo("ACTIVE"))+ .body(CLUSTER_ROLES + "[1].RoleArn", equalTo(LAMBDA_ROLE))+ .body(CLUSTER_ROLES + "[1].Status", equalTo("ACTIVE"))+ .body(not(containsString("<FeatureName></FeatureName>")));+ }++ @Test+ @Order(3)+ void refusesAClusterRoleAlreadyAssociated() {+ clusterRole("AddRoleToDBCluster", S3_ROLE).formParam("FeatureName", "s3Export")+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("DBClusterRoleAlreadyExists"));+ // DBClusterRoleAlreadyExists covers the role ARN only, so another role for the same feature is taken.+ String other = "arn:aws:iam::000000000000:role/other";+ clusterRole("AddRoleToDBCluster", other).formParam("FeatureName", "s3Import")+ .when().post("/").then().statusCode(200);+ clusterRole("RemoveRoleFromDBCluster", other)+ .when().post("/").then().statusCode(200);+ }++ @Test+ @Order(4)+ void removesAClusterRoleAndRefusesOneNotAssociated() {+ // A feature name that does not match the association is not that association.+ clusterRole("RemoveRoleFromDBCluster", S3_ROLE).formParam("FeatureName", "Lambda")+ .when().post("/").then().statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("DBClusterRoleNotFound"));++ clusterRole("RemoveRoleFromDBCluster", S3_ROLE)+ .when().post("/").then().statusCode(200)+ .body(containsString("<RemoveRoleFromDBClusterResponse"));+ clusterRole("RemoveRoleFromDBCluster", S3_ROLE)+ .when().post("/").then().statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("DBClusterRoleNotFound"));++ query("DescribeDBClusters").formParam("DBClusterIdentifier", CLUSTER)+ .when().post("/").then().statusCode(200)+ .body(CLUSTER_ROLES + ".RoleArn", equalTo(LAMBDA_ROLE))+ .body(not(containsString(S3_ROLE)));+ }++ @Test+ @Order(5)+ void addsAndRemovesInstanceRolesByFeature() {+ instanceRole("AddRoleToDBInstance", S3_ROLE, "s3Import")+ .when().post("/").then().statusCode(200)+ .body(containsString("<AddRoleToDBInstanceResponse"));+ instanceRole("AddRoleToDBInstance", LAMBDA_ROLE, "Lambda")+ .when().post("/").then().statusCode(200);++ query("DescribeDBInstances").formParam("DBInstanceIdentifier", INSTANCE)+ .when().post("/").then().statusCode(200)+ .body(INSTANCE_ROLES + "[0].RoleArn", equalTo(S3_ROLE))+ .body(INSTANCE_ROLES + "[0].FeatureName", equalTo("s3Import"))+ .body(INSTANCE_ROLES + "[0].Status", equalTo("ACTIVE"))+ .body(INSTANCE_ROLES + "[1].FeatureName", equalTo("Lambda"));++ // The same role for another feature, or another role for the same feature.+ instanceRole("AddRoleToDBInstance", S3_ROLE, "s3Export")+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("DBInstanceRoleAlreadyExists"));+ instanceRole("AddRoleToDBInstance", "arn:aws:iam::000000000000:role/other", "Lambda")+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("DBInstanceRoleAlreadyExists"));++ instanceRole("RemoveRoleFromDBInstance", S3_ROLE, "Lambda")+ .when().post("/").then().statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("DBInstanceRoleNotFound"));+ instanceRole("RemoveRoleFromDBInstance", S3_ROLE, "s3Import")+ .when().post("/").then().statusCode(200)+ .body(containsString("<RemoveRoleFromDBInstanceResponse"));++ query("DescribeDBInstances").formParam("DBInstanceIdentifier", INSTANCE)+ .when().post("/").then().statusCode(200)+ .body(INSTANCE_ROLES + ".RoleArn", equalTo(LAMBDA_ROLE));+ }++ @Test+ @Order(6)+ void requiresTheParametersTheModelRequires() {+ query("AddRoleToDBInstance").formParam("DBInstanceIdentifier", INSTANCE).formParam("RoleArn", S3_ROLE)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("MissingParameter"));+ query("AddRoleToDBCluster").formParam("DBClusterIdentifier", CLUSTER)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("MissingParameter"));+ }++ @Test+ @Order(7)+ void refusesUnknownResources() {+ query("AddRoleToDBCluster").formParam("DBClusterIdentifier", "no-such-cluster").formParam("RoleArn", S3_ROLE)+ .when().post("/").then().statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("DBClusterNotFoundFault"));+ query("AddRoleToDBInstance").formParam("DBInstanceIdentifier", "no-such-instance")+ .formParam("RoleArn", S3_ROLE).formParam("FeatureName", "s3Import")+ .when().post("/").then().statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("DBInstanceNotFound"));+ }++ @Test+ @Order(8)+ void refusesAStoppedResource() {+ query("StopDBInstance").formParam("DBInstanceIdentifier", INSTANCE)+ .when().post("/").then().statusCode(200);+ instanceRole("AddRoleToDBInstance", S3_ROLE, "s3Import")+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidDBInstanceState"));+ query("StartDBInstance").formParam("DBInstanceIdentifier", INSTANCE)+ .when().post("/").then().statusCode(200);++ query("StopDBCluster").formParam("DBClusterIdentifier", CLUSTER)+ .when().post("/").then().statusCode(200);+ clusterRole("AddRoleToDBCluster", S3_ROLE)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidDBClusterStateFault"));+ query("StartDBCluster").formParam("DBClusterIdentifier", CLUSTER)+ .when().post("/").then().statusCode(200);+ }++ @Test+ @Order(9)+ void createDbClusterAssociatesTheRolesItNames() {+ query("CreateDBCluster")+ .formParam("DBClusterIdentifier", "roles-at-create")+ .formParam("Engine", "aurora-postgresql")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .formParam("AssociatedRoles.DBClusterAssociatedRole.1.RoleArn", S3_ROLE)+ .formParam("AssociatedRoles.DBClusterAssociatedRole.1.FeatureName", "s3Import")+ .formParam("AssociatedRoles.DBClusterAssociatedRole.2.RoleArn", LAMBDA_ROLE)+ .when().post("/").then().statusCode(200)+ .body("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.AssociatedRoles.DBClusterRole[0].RoleArn",+ equalTo(S3_ROLE))+ .body("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.AssociatedRoles.DBClusterRole[1].RoleArn",+ equalTo(LAMBDA_ROLE));+ }++ @Test+ @Order(10)+ void createDbClusterNamingARoleTwiceCreatesNothing() {+ query("CreateDBCluster")+ .formParam("DBClusterIdentifier", "roles-duplicate")+ .formParam("Engine", "aurora-postgresql")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .formParam("AssociatedRoles.member.1.RoleArn", S3_ROLE)+ .formParam("AssociatedRoles.member.2.RoleArn", S3_ROLE)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("DBClusterRoleAlreadyExists"));+ query("DescribeDBClusters").formParam("DBClusterIdentifier", "roles-duplicate")+ .when().post("/").then().statusCode(404);+ }++ @Test+ @Order(11)+ void createDbClusterRefusesAnEntryWithoutARoleArn() {+ query("CreateDBCluster")+ .formParam("DBClusterIdentifier", "roles-no-arn")+ .formParam("Engine", "aurora-postgresql")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .formParam("AssociatedRoles.DBClusterAssociatedRole.1.FeatureName", "s3Import")+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("MissingParameter"));+ query("DescribeDBClusters").formParam("DBClusterIdentifier", "roles-no-arn")+ .when().post("/").then().statusCode(404);+ }++ @Test+ @Order(12)+ void createDbClusterReadsEveryEntryPastAGap() {+ query("CreateDBCluster")+ .formParam("DBClusterIdentifier", "roles-gap")+ .formParam("Engine", "aurora-postgresql")+ .formParam("MasterUsername", "admin")+ .formParam("MasterUserPassword", "password123")+ .formParam("AssociatedRoles.DBClusterAssociatedRole.1.RoleArn", S3_ROLE)+ .formParam("AssociatedRoles.DBClusterAssociatedRole.3.RoleArn", LAMBDA_ROLE)+ .when().post("/").then().statusCode(200)+ .body("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.AssociatedRoles.DBClusterRole.RoleArn",+ contains(S3_ROLE, LAMBDA_ROLE));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.javaindex 1710239fba..58d33a1d05 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java@@ -5,11 +5,14 @@ import io.github.hectorvent.floci.core.storage.PersistentStorage;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import java.nio.file.Files;import java.nio.file.Path;+import java.util.List;import java.util.Map;import java.util.Optional;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;class DbClusterPersistenceTest {@@ -39,4 +42,51 @@ class DbClusterPersistenceTest {assertEquals(16.0, restored.get().getServerlessV2MaxCapacity());assertEquals(600, restored.get().getServerlessV2SecondsUntilAutoPause());}++ @Test+ void associatedRolesPersistAcrossInstances(@TempDir Path directory) {+ DbCluster cluster = new DbCluster();+ cluster.setDbClusterIdentifier("roles-cluster");+ cluster.getAssociatedRoles().add(new DbRoleAssociation("arn:aws:iam::000000000000:role/a", "s3Import"));+ cluster.getAssociatedRoles().add(new DbRoleAssociation("arn:aws:iam::000000000000:role/b", null));+ DbInstance instance = new DbInstance();+ instance.setDbInstanceIdentifier("roles-instance");+ instance.getAssociatedRoles().add(new DbRoleAssociation("arn:aws:iam::000000000000:role/c", "Lambda"));++ Path clusters = directory.resolve("rds-clusters.json");+ new PersistentStorage<String, DbCluster>(clusters, new TypeReference<Map<String, DbCluster>>() {})+ .put(cluster.getDbClusterIdentifier(), cluster);+ Path instances = directory.resolve("rds-instances.json");+ new PersistentStorage<String, DbInstance>(instances, new TypeReference<Map<String, DbInstance>>() {})+ .put(instance.getDbInstanceIdentifier(), instance);++ PersistentStorage<String, DbCluster> clusterReader = new PersistentStorage<>(+ clusters, new TypeReference<Map<String, DbCluster>>() {});+ clusterReader.load();+ List<DbRoleAssociation> clusterRoles = clusterReader.get("roles-cluster").orElseThrow().getAssociatedRoles();+ assertEquals(2, clusterRoles.size());+ assertEquals("arn:aws:iam::000000000000:role/a", clusterRoles.get(0).getRoleArn());+ assertEquals("s3Import", clusterRoles.get(0).getFeatureName());+ assertEquals(DbRoleAssociation.ACTIVE, clusterRoles.get(0).getStatus());+ assertNull(clusterRoles.get(1).getFeatureName());++ PersistentStorage<String, DbInstance> instanceReader = new PersistentStorage<>(+ instances, new TypeReference<Map<String, DbInstance>>() {});+ instanceReader.load();+ List<DbRoleAssociation> instanceRoles = instanceReader.get("roles-instance").orElseThrow().getAssociatedRoles();+ assertEquals(1, instanceRoles.size());+ assertEquals("Lambda", instanceRoles.get(0).getFeatureName());+ }++ @Test+ void stateSavedBeforeRoleAssociationsLoadsWithNone(@TempDir Path directory) throws Exception {+ Path file = directory.resolve("rds-clusters.json");+ Files.writeString(file, "{\"legacy-cluster\":{\"dbClusterIdentifier\":\"legacy-cluster\"}}");++ PersistentStorage<String, DbCluster> reader = new PersistentStorage<>(+ file, new TypeReference<Map<String, DbCluster>>() {});+ reader.load();++ assertTrue(reader.get("legacy-cluster").orElseThrow().getAssociatedRoles().isEmpty());+ }}