mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-serverless): add running workgroups and Data API WorkgroupName support (#5012)
* feat(redshift-serverless): add running workgroups and Data API WorkgroupName support Redshift Serverless workgroups get full CRUD (Create/Get/List/Update/Delete), tagging by ARN, and the AWS::RedshiftServerless::Namespace and ::Workgroup CloudFormation types with dotted Fn::GetAtt keys taken from the registry schema. A namespace has at most one workgroup, and DeleteNamespace is refused while one is attached. Each workgroup runs a PostgreSQL container behind an authenticating proxy, sharing the managers and the proxy port pool with provisioned Redshift. Add GetCredentials, accept WorkgroupName (name or ARN) in the Redshift Data API, and push a changed namespace adminUserPassword down to the running backend. The runtime is re-attached when Floci restarts. Not covered: snapshots, usage limits, endpoint access, and COPY/UNLOAD/Spectrum on workgroups. * fix(redshift-serverless): stop the runtime when workgroup creation fails after it started If persisting the workgroup record failed after the container and proxy were already running, the runtime was left behind with no record. createWorkgroup now stops it (best effort) and releases the endpoint on the failure path. Fix the CloudFormation error for a NamespaceName change: suggesting a new WorkgroupName can never succeed because a namespace holds only one workgroup. * fix(redshift-serverless): reset omitted CloudFormation properties and order startup observers When UpdateStack drops a property from the template, the provisioner now sends its default (BaseCapacity, EnhancedVpcRouting, PubliclyAccessible, Port, TrackName, PricePerformanceTarget) instead of keeping the stored value, which matches CloudFormation semantics. MaxCapacity has no default and keeps its stored value. Give the workgroup StartupEvent observer a @Priority after RedshiftService so every persisted cluster has reserved its proxy port before workgroups restore theirs. Also remove an unused import and move DEFAULT_DATABASE to the top of RedshiftContainerManager. * fix(redshift-serverless): address review findings on password rotation and namespace updates - Roll the backend password back when a rotation cannot be completed or stored, and apply it last so validation failures never leave the backend ahead of the stored namespace. - Keep a workgroup endpoint reserved when its runtime cannot be stopped during clear(). - Reject an in-place DbName change in CloudFormation, since it is fixed at creation. - Reset an omitted KmsKeyId and DefaultIamRoleArn on CloudFormation updates. * fix(redshift-serverless): keep rollback failures from masking errors and drop stale GetAtt role - Do not reset the proxy password when the role restore fails, and attach restore failures to the original exception instead of replacing it. - Remove Namespace.DefaultIamRoleArn from the stack resource when an update no longer declares a default role. * docs: correct the Redshift Serverless operation count in the service matrix * fix(redshift-serverless): expose Workgroup.ConfigParameters through Fn::GetAtt * fix(redshift-serverless): parse ConfigParameters resolved from a GetAtt attribute * docs(redshift-serverless): list every unsupported operation group
This commit is contained in:
1 parent
a84a8a0435
commit
99a6b4050c
36 files changed
+4028
-81
No files matched your search
+11
@@ -90,6 +90,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetri
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftClusterCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftServerlessCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner;
|
||||
@@ -129,6 +130,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.github.hectorvent.floci.services.route53.Route53Service;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
|
||||
@@ -218,6 +220,7 @@ final class CfnProvisionerFixture {
|
||||
private WafV2Service wafV2Service;
|
||||
private BackupService backupService;
|
||||
private RedshiftService redshiftService;
|
||||
private RedshiftServerlessService redshiftServerlessService;
|
||||
private CloudMapService cloudMapService;
|
||||
private CloudFormationResourceRegistry resourceRegistry;
|
||||
private boolean registryChosenByTest;
|
||||
@@ -433,6 +436,9 @@ final class CfnProvisionerFixture {
|
||||
if (redshiftService != null) {
|
||||
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
|
||||
}
|
||||
if (redshiftServerlessService != null) {
|
||||
discovered.add(new RedshiftServerlessCfnProvisioner(redshiftServerlessService));
|
||||
}
|
||||
if (cloudMapService != null) {
|
||||
discovered.add(new CloudMapCfnProvisioner(cloudMapService));
|
||||
}
|
||||
@@ -693,6 +699,11 @@ final class CfnProvisionerFixture {
|
||||
return redshiftService(s);
|
||||
}
|
||||
|
||||
public Builder redshiftServerlessService(RedshiftServerlessService s) {
|
||||
this.redshiftServerlessService = s;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder cloudMap(CloudMapService v) {
|
||||
this.cloudMapService = v;
|
||||
return this;
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessRuntime;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::RedshiftServerless::Namespace} and its
|
||||
* {@code AWS::RedshiftServerless::Workgroup} through a stack. An unmapped type is stubbed as
|
||||
* CREATE_COMPLETE with a fake ARN, so the assertions that matter are the exact {@code Fn::GetAtt}
|
||||
* keys and that what they return is what the Redshift Serverless API serves.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class RedshiftServerlessCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261003/us-east-1/cloudformation/aws4_request";
|
||||
private static final String RS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261003/us-east-1/redshift-serverless/aws4_request";
|
||||
private static final String STACK = "redshift-serverless-cfn-it";
|
||||
private static final String NAMESPACE = "rs-cfn-it-ns";
|
||||
private static final String WORKGROUP = "rs-cfn-it-wg";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {"Capacity": {"Type": "Number"}},
|
||||
"Resources": {
|
||||
"Ns": {
|
||||
"Type": "AWS::RedshiftServerless::Namespace",
|
||||
"Properties": {
|
||||
"NamespaceName": "%s",
|
||||
"AdminUsername": "admin",
|
||||
"AdminUserPassword": "Secret123!",
|
||||
"DbName": "analytics",
|
||||
"LogExports": ["userlog"],
|
||||
"Tags": [{"Key": "env", "Value": "dev"}]
|
||||
}
|
||||
},
|
||||
"Wg": {
|
||||
"Type": "AWS::RedshiftServerless::Workgroup",
|
||||
"Properties": {
|
||||
"WorkgroupName": "%s",
|
||||
"NamespaceName": {"Ref": "Ns"},
|
||||
"BaseCapacity": {"Ref": "Capacity"},
|
||||
"PubliclyAccessible": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"NsRef": {"Value": {"Ref": "Ns"}},
|
||||
"NsArn": {"Value": {"Fn::GetAtt": ["Ns", "Namespace.NamespaceArn"]}},
|
||||
"NsId": {"Value": {"Fn::GetAtt": ["Ns", "Namespace.NamespaceId"]}},
|
||||
"NsDb": {"Value": {"Fn::GetAtt": ["Ns", "Namespace.DbName"]}},
|
||||
"NsStatus": {"Value": {"Fn::GetAtt": ["Ns", "Namespace.Status"]}},
|
||||
"WgRef": {"Value": {"Ref": "Wg"}},
|
||||
"WgArn": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.WorkgroupArn"]}},
|
||||
"WgId": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.WorkgroupId"]}},
|
||||
"WgNamespace": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.NamespaceName"]}},
|
||||
"WgAddress": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.Endpoint.Address"]}},
|
||||
"WgPort": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.Endpoint.Port"]}},
|
||||
"WgBase": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.BaseCapacity"]}},
|
||||
"WgStatus": {"Value": {"Fn::GetAtt": ["Wg", "Workgroup.Status"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(NAMESPACE, WORKGROUP);
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* The metadata behaviour under test needs no PostgreSQL container, so the runtime is replaced:
|
||||
* these tests then run without Docker, and the real container and proxy are exercised by
|
||||
* {@code RedshiftServerlessRuntimeIntegrationTest}.
|
||||
*/
|
||||
@InjectMock
|
||||
RedshiftServerlessRuntime runtime;
|
||||
|
||||
@BeforeEach
|
||||
void stubRuntime() {
|
||||
when(runtime.generatePassword()).thenReturn("Generated123");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteANamespaceAndWorkgroup() {
|
||||
cloudFormation("CreateStack", "32");
|
||||
String created = describeStacks("CREATE_COMPLETE");
|
||||
|
||||
assertEquals(NAMESPACE, outputValue(created, "NsRef"));
|
||||
assertEquals(WORKGROUP, outputValue(created, "WgRef"));
|
||||
assertEquals("analytics", outputValue(created, "NsDb"));
|
||||
assertEquals("AVAILABLE", outputValue(created, "NsStatus"));
|
||||
assertEquals("AVAILABLE", outputValue(created, "WgStatus"));
|
||||
assertEquals(NAMESPACE, outputValue(created, "WgNamespace"));
|
||||
assertEquals("32", outputValue(created, "WgBase"));
|
||||
assertTrue(outputValue(created, "WgArn").contains(":workgroup/" + outputValue(created, "WgId")),
|
||||
"GetAtt must be the ARN of the workgroup, not the 'Workgroup.WorkgroupArn' literal");
|
||||
assertNotEquals("Wg.Workgroup.Endpoint.Address", outputValue(created, "WgAddress"));
|
||||
assertTrue(Integer.parseInt(outputValue(created, "WgPort")) > 0);
|
||||
|
||||
call("GetNamespace", "{\"namespaceName\":\"" + NAMESPACE + "\"}")
|
||||
.statusCode(200)
|
||||
.body("namespace.namespaceArn", equalTo(outputValue(created, "NsArn")))
|
||||
.body("namespace.namespaceId", equalTo(outputValue(created, "NsId")))
|
||||
.body("namespace.logExports", hasItem("userlog"));
|
||||
call("GetWorkgroup", "{\"workgroupName\":\"" + WORKGROUP + "\"}")
|
||||
.statusCode(200)
|
||||
.body("workgroup.workgroupArn", equalTo(outputValue(created, "WgArn")))
|
||||
.body("workgroup.baseCapacity", equalTo(32))
|
||||
.body("workgroup.publiclyAccessible", equalTo(true))
|
||||
.body("workgroup.endpoint.address", equalTo(outputValue(created, "WgAddress")));
|
||||
|
||||
cloudFormation("UpdateStack", "64");
|
||||
String updated = describeStacks("UPDATE_COMPLETE");
|
||||
|
||||
// The capacity changes on the same workgroup; nothing is replaced.
|
||||
assertEquals(outputValue(created, "WgId"), outputValue(updated, "WgId"));
|
||||
assertEquals("64", outputValue(updated, "WgBase"));
|
||||
call("GetWorkgroup", "{\"workgroupName\":\"" + WORKGROUP + "\"}")
|
||||
.statusCode(200)
|
||||
.body("workgroup.baseCapacity", equalTo(64));
|
||||
|
||||
cloudFormation("DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
|
||||
// The workgroup is deleted before the namespace, which would otherwise be refused.
|
||||
call("GetWorkgroup", "{\"workgroupName\":\"" + WORKGROUP + "\"}").statusCode(404);
|
||||
call("GetNamespace", "{\"namespaceName\":\"" + NAMESPACE + "\"}").statusCode(404);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String capacity) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", STACK);
|
||||
if (!"DeleteStack".equals(action)) {
|
||||
request.formParam("TemplateBody", TEMPLATE);
|
||||
request.formParam("Parameters.member.1.ParameterKey", "Capacity");
|
||||
request.formParam("Parameters.member.1.ParameterValue", capacity);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
Map<String, String> outputs = XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
|
||||
return outputs.get(key);
|
||||
}
|
||||
|
||||
private static ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "RedshiftServerless." + action)
|
||||
.header("Authorization", RS_AUTH)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.WorkgroupSettings;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.PricePerformanceTarget;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Workgroup;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The Redshift Serverless CFN provisioner in isolation, against a mocked service. */
|
||||
class RedshiftServerlessCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAMESPACE_TYPE = "AWS::RedshiftServerless::Namespace";
|
||||
private static final String WORKGROUP_TYPE = "AWS::RedshiftServerless::Workgroup";
|
||||
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ns-id";
|
||||
private static final String WORKGROUP_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/wg-id";
|
||||
|
||||
private final RedshiftServerlessService service = mock(RedshiftServerlessService.class);
|
||||
private final RedshiftServerlessCfnProvisioner provisioner = new RedshiftServerlessCfnProvisioner(service);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource(String type, String priorPhysicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("MyResource");
|
||||
r.setResourceType(type);
|
||||
r.setPhysicalId(priorPhysicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private static Namespace namespace(String name) {
|
||||
Namespace namespace = new Namespace();
|
||||
namespace.setNamespaceName(name);
|
||||
namespace.setNamespaceId("ns-id");
|
||||
namespace.setNamespaceArn(NAMESPACE_ARN);
|
||||
namespace.setAdminUsername("admin");
|
||||
namespace.setDbName("dev");
|
||||
namespace.setKmsKeyId("AWS_OWNED_KMS_KEY");
|
||||
namespace.setIamRoles(new ArrayList<>(List.of("arn:aws:iam::000000000000:role/a")));
|
||||
namespace.setLogExports(new ArrayList<>(List.of("userlog")));
|
||||
namespace.setStatus("AVAILABLE");
|
||||
namespace.setCreationDate(Instant.parse("2026-10-03T00:00:00Z"));
|
||||
return namespace;
|
||||
}
|
||||
|
||||
private static Workgroup workgroup(String name, String namespaceName) {
|
||||
Workgroup workgroup = new Workgroup();
|
||||
workgroup.setWorkgroupName(name);
|
||||
workgroup.setWorkgroupId("wg-id");
|
||||
workgroup.setWorkgroupArn(WORKGROUP_ARN);
|
||||
workgroup.setNamespaceName(namespaceName);
|
||||
workgroup.setBaseCapacity(32);
|
||||
workgroup.setTrackName("current");
|
||||
workgroup.setStatus("AVAILABLE");
|
||||
workgroup.setCreationDate(Instant.parse("2026-10-03T00:00:00Z"));
|
||||
workgroup.setSecurityGroupIds(new ArrayList<>(List.of("sg-1", "sg-2")));
|
||||
workgroup.setEndpoint(new Endpoint("localhost", 7100));
|
||||
workgroup.setConfigParameters(new ArrayList<>(List.of(new ConfigParameter("datestyle", "ISO, MDY"))));
|
||||
return workgroup;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNamespaceSendsPropertiesAndRecordsEveryDottedAttribute() {
|
||||
when(service.createNamespace(eq("my-ns"), eq("admin"), eq("Secret123"), eq("analytics"), isNull(),
|
||||
isNull(), anyList(), anyList(), anyMap(), eq(REGION))).thenReturn(namespace("my-ns"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("AdminUsername", "admin");
|
||||
props.put("AdminUserPassword", "Secret123");
|
||||
props.put("DbName", "analytics");
|
||||
props.putObject("Tags").put("env", "dev");
|
||||
StackResource r = resource(NAMESPACE_TYPE, null);
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
assertEquals("my-ns", r.getPhysicalId());
|
||||
Map<String, String> attributes = r.getAttributes();
|
||||
assertEquals("my-ns", attributes.get("Namespace.NamespaceName"));
|
||||
assertEquals("ns-id", attributes.get("Namespace.NamespaceId"));
|
||||
assertEquals(NAMESPACE_ARN, attributes.get("Namespace.NamespaceArn"));
|
||||
assertEquals("dev", attributes.get("Namespace.DbName"));
|
||||
assertEquals("AWS_OWNED_KMS_KEY", attributes.get("Namespace.KmsKeyId"));
|
||||
assertEquals("AVAILABLE", attributes.get("Namespace.Status"));
|
||||
assertEquals("2026-10-03T00:00:00Z", attributes.get("Namespace.CreationDate"));
|
||||
assertEquals("admin", attributes.get("Namespace.AdminUsername"));
|
||||
assertEquals("arn:aws:iam::000000000000:role/a", attributes.get("Namespace.IamRoles"));
|
||||
assertEquals("userlog", attributes.get("Namespace.LogExports"));
|
||||
assertFalse(attributes.containsKey("Namespace.DefaultIamRoleArn"));
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.forClass(Map.class);
|
||||
verify(service).createNamespace(eq("my-ns"), eq("admin"), eq("Secret123"), eq("analytics"), isNull(),
|
||||
isNull(), anyList(), anyList(), tags.capture(), eq(REGION));
|
||||
assertEquals(Map.of("env", "dev"), tags.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedNamespaceGetsALowercaseGeneratedNameThatIsStableAcrossUpdates() {
|
||||
when(service.createNamespace(any(), any(), any(), any(), any(), any(), anyList(), anyList(), anyMap(),
|
||||
eq(REGION)))
|
||||
.thenAnswer(inv -> namespace(inv.getArgument(0)));
|
||||
StackResource created = resource(NAMESPACE_TYPE, null);
|
||||
|
||||
provisioner.provision(created, mapper.createObjectNode(), ctx(null));
|
||||
|
||||
String generated = created.getPhysicalId();
|
||||
assertTrue(generated.startsWith("my-stack-myresource-"), generated);
|
||||
assertEquals(generated, generated.toLowerCase());
|
||||
|
||||
when(service.getNamespace(generated, REGION)).thenReturn(namespace(generated));
|
||||
when(service.reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(REGION)))
|
||||
.thenReturn(namespace(generated));
|
||||
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
|
||||
StackResource updated = resource(NAMESPACE_TYPE, generated);
|
||||
|
||||
provisioner.provision(updated, mapper.createObjectNode(), ctx(generated));
|
||||
|
||||
assertEquals(generated, updated.getPhysicalId());
|
||||
verify(service).reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNamespaceUpdatesInPlaceAndRemovesTagsTheTemplateDropped() {
|
||||
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
|
||||
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), eq("custom-key"), isNull(), anyList(),
|
||||
anyList(), eq(REGION))).thenReturn(namespace("my-ns"));
|
||||
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of("old", "1", "keep", "2"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("KmsKeyId", "custom-key");
|
||||
props.putObject("Tags").put("keep", "2");
|
||||
StackResource r = resource(NAMESPACE_TYPE, "my-ns");
|
||||
|
||||
provisioner.provision(r, props, ctx("my-ns"));
|
||||
|
||||
verify(service, never()).createNamespace(any(), any(), any(), any(), any(), any(), anyList(), anyList(),
|
||||
anyMap(), any());
|
||||
verify(service).untagResource(NAMESPACE_ARN, List.of("old"), REGION);
|
||||
verify(service).tagResource(NAMESPACE_ARN, Map.of("keep", "2"), REGION);
|
||||
assertEquals("my-ns", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNamespaceRejectsADbNameChangeBecauseItIsFixedAtCreation() {
|
||||
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("DbName", "analytics");
|
||||
StackResource r = resource(NAMESPACE_TYPE, "my-ns");
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("my-ns")));
|
||||
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
verify(service, never()).reconcileNamespace(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNamespaceSendsOmittedKmsKeyAndDefaultRoleAsNullSoTheServiceResetsThem() {
|
||||
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
|
||||
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(), anyList(),
|
||||
eq(REGION))).thenReturn(namespace("my-ns"));
|
||||
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("DbName", "dev");
|
||||
StackResource r = resource(NAMESPACE_TYPE, "my-ns");
|
||||
|
||||
provisioner.provision(r, props, ctx("my-ns"));
|
||||
|
||||
verify(service).reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(),
|
||||
anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNamespaceDropsTheDefaultRoleAttributeWhenTheTemplateNoLongerDeclaresIt() {
|
||||
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
|
||||
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(), anyList(),
|
||||
eq(REGION))).thenReturn(namespace("my-ns"));
|
||||
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("NamespaceName", "my-ns");
|
||||
StackResource r = resource(NAMESPACE_TYPE, "my-ns");
|
||||
r.getAttributes().put("Namespace.DefaultIamRoleArn", "arn:aws:iam::000000000000:role/old");
|
||||
|
||||
provisioner.provision(r, props, ctx("my-ns"));
|
||||
|
||||
assertFalse(r.getAttributes().containsKey("Namespace.DefaultIamRoleArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupParsesConfigParametersResolvedFromAnotherWorkgroupAttribute() {
|
||||
when(service.createWorkgroup(eq("my-wg"), eq("my-ns"), any(WorkgroupSettings.class), anyMap(), eq(REGION)))
|
||||
.thenReturn(workgroup("my-wg", "my-ns"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("ConfigParameters", "[{\"ParameterKey\":\"datestyle\",\"ParameterValue\":\"ISO, MDY\"}]");
|
||||
|
||||
provisioner.provision(resource(WORKGROUP_TYPE, null), props, ctx(null));
|
||||
|
||||
ArgumentCaptor<WorkgroupSettings> settings = ArgumentCaptor.forClass(WorkgroupSettings.class);
|
||||
verify(service).createWorkgroup(eq("my-wg"), eq("my-ns"), settings.capture(), anyMap(), eq(REGION));
|
||||
assertEquals(1, settings.getValue().configParameters().size());
|
||||
assertEquals("datestyle", settings.getValue().configParameters().get(0).getParameterKey());
|
||||
assertEquals("ISO, MDY", settings.getValue().configParameters().get(0).getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupRejectsConfigParametersThatAreNotAList() {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("ConfigParameters", "not-json");
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(WORKGROUP_TYPE, null), props, ctx(null)));
|
||||
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupMapsEveryPropertyAndRecordsTheEndpointAttributes() {
|
||||
when(service.createWorkgroup(eq("my-wg"), eq("my-ns"), any(WorkgroupSettings.class), anyMap(), eq(REGION)))
|
||||
.thenReturn(workgroup("my-wg", "my-ns"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("BaseCapacity", 32);
|
||||
props.put("MaxCapacity", 64);
|
||||
props.put("EnhancedVpcRouting", false);
|
||||
props.put("PubliclyAccessible", true);
|
||||
props.put("Port", 5440);
|
||||
props.put("TrackName", "trailing");
|
||||
props.putArray("SecurityGroupIds").add("sg-1");
|
||||
props.putArray("SubnetIds").add("subnet-1");
|
||||
props.putArray("ConfigParameters").addObject()
|
||||
.put("ParameterKey", "datestyle").put("ParameterValue", "ISO, MDY");
|
||||
props.putObject("PricePerformanceTarget").put("Status", "ENABLED").put("Level", 50);
|
||||
StackResource r = resource(WORKGROUP_TYPE, null);
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<WorkgroupSettings> settings = ArgumentCaptor.forClass(WorkgroupSettings.class);
|
||||
verify(service).createWorkgroup(eq("my-wg"), eq("my-ns"), settings.capture(), anyMap(), eq(REGION));
|
||||
WorkgroupSettings sent = settings.getValue();
|
||||
assertEquals(32, sent.baseCapacity());
|
||||
assertEquals(64, sent.maxCapacity());
|
||||
assertEquals(Boolean.FALSE, sent.enhancedVpcRouting());
|
||||
assertEquals(Boolean.TRUE, sent.publiclyAccessible());
|
||||
assertEquals(5440, sent.port());
|
||||
assertEquals("trailing", sent.trackName());
|
||||
assertEquals("datestyle", sent.configParameters().get(0).getParameterKey());
|
||||
PricePerformanceTarget target = sent.pricePerformanceTarget();
|
||||
assertEquals("ENABLED", target.getStatus());
|
||||
assertEquals(50, target.getLevel());
|
||||
|
||||
assertEquals("my-wg", r.getPhysicalId());
|
||||
Map<String, String> attributes = r.getAttributes();
|
||||
assertEquals("wg-id", attributes.get("Workgroup.WorkgroupId"));
|
||||
assertEquals(WORKGROUP_ARN, attributes.get("Workgroup.WorkgroupArn"));
|
||||
assertEquals("my-ns", attributes.get("Workgroup.NamespaceName"));
|
||||
assertEquals("localhost", attributes.get("Workgroup.Endpoint.Address"));
|
||||
assertEquals("7100", attributes.get("Workgroup.Endpoint.Port"));
|
||||
assertEquals("32", attributes.get("Workgroup.BaseCapacity"));
|
||||
assertEquals("sg-1,sg-2", attributes.get("Workgroup.SecurityGroupIds"));
|
||||
assertEquals("[{\"ParameterKey\":\"datestyle\",\"ParameterValue\":\"ISO, MDY\"}]",
|
||||
attributes.get("Workgroup.ConfigParameters"));
|
||||
assertEquals("AVAILABLE", attributes.get("Workgroup.Status"));
|
||||
assertFalse(attributes.containsKey("Workgroup.MaxCapacity"), "unset on the stored workgroup");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorkgroupUpdatesInPlaceAndRejectsANamespaceChange() {
|
||||
when(service.getWorkgroup("my-wg", REGION)).thenReturn(workgroup("my-wg", "my-ns"));
|
||||
when(service.updateWorkgroup(eq("my-wg"), any(WorkgroupSettings.class), eq(REGION)))
|
||||
.thenReturn(workgroup("my-wg", "my-ns"));
|
||||
when(service.listTagsForResource(WORKGROUP_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("BaseCapacity", 64);
|
||||
|
||||
provisioner.provision(resource(WORKGROUP_TYPE, "my-wg"), props, ctx("my-wg"));
|
||||
|
||||
verify(service).updateWorkgroup(eq("my-wg"), any(WorkgroupSettings.class), eq(REGION));
|
||||
verify(service, never()).createWorkgroup(any(), any(), any(), any(), any());
|
||||
|
||||
ObjectNode moved = mapper.createObjectNode();
|
||||
moved.put("WorkgroupName", "my-wg");
|
||||
moved.put("NamespaceName", "other-ns");
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(WORKGROUP_TYPE, "my-wg"), moved, ctx("my-wg")));
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateThatOmitsAPropertyResetsItToTheDefaultInsteadOfKeepingTheStoredValue() {
|
||||
when(service.getWorkgroup("my-wg", REGION)).thenReturn(workgroup("my-wg", "my-ns"));
|
||||
when(service.updateWorkgroup(eq("my-wg"), any(WorkgroupSettings.class), eq(REGION)))
|
||||
.thenReturn(workgroup("my-wg", "my-ns"));
|
||||
when(service.listTagsForResource(WORKGROUP_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
|
||||
provisioner.provision(resource(WORKGROUP_TYPE, "my-wg"), props, ctx("my-wg"));
|
||||
|
||||
ArgumentCaptor<WorkgroupSettings> settings = ArgumentCaptor.forClass(WorkgroupSettings.class);
|
||||
verify(service).updateWorkgroup(eq("my-wg"), settings.capture(), eq(REGION));
|
||||
WorkgroupSettings sent = settings.getValue();
|
||||
assertEquals(RedshiftServerlessService.DEFAULT_BASE_CAPACITY, sent.baseCapacity());
|
||||
assertEquals(Boolean.FALSE, sent.enhancedVpcRouting());
|
||||
assertEquals(Boolean.FALSE, sent.publiclyAccessible());
|
||||
assertEquals(RedshiftServerlessService.DEFAULT_PORT, sent.port());
|
||||
assertEquals(RedshiftServerlessService.DEFAULT_TRACK_NAME, sent.trackName());
|
||||
assertEquals("DISABLED", sent.pricePerformanceTarget().getStatus());
|
||||
assertTrue(sent.configParameters().isEmpty());
|
||||
assertTrue(sent.subnetIds().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonNumericCapacityIsAValidationError() {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("WorkgroupName", "my-wg");
|
||||
props.put("NamespaceName", "my-ns");
|
||||
props.put("BaseCapacity", "many");
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(WORKGROUP_TYPE, null), props, ctx(null)));
|
||||
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
verify(service, never()).createWorkgroup(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesOnlyNotFoundAndLetsOtherFailuresReachTheStack() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
|
||||
.when(service).deleteWorkgroup("gone-wg", REGION);
|
||||
provisioner.delete(WORKGROUP_TYPE, "gone-wg", REGION);
|
||||
|
||||
doThrow(new AwsException("ConflictException", "still has a workgroup", 409))
|
||||
.when(service).deleteNamespace("busy-ns", REGION);
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(NAMESPACE_TYPE, "busy-ns", REGION));
|
||||
assertEquals("ConflictException", failure.getErrorCode());
|
||||
|
||||
provisioner.delete(NAMESPACE_TYPE, "ok-ns", REGION);
|
||||
verify(service).deleteNamespace("ok-ns", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theProvisionerServesBothTypes() {
|
||||
assertEquals(Set.of(NAMESPACE_TYPE, WORKGROUP_TYPE), provisioner.resourceTypes());
|
||||
}
|
||||
}
|
||||
@@ -1846,4 +1846,28 @@ class RedshiftServiceTest {
|
||||
assertEquals(PasswordValidator.AuthResult.PASSTHROUGH,
|
||||
validator.validate("someone-else", "whatever"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedProxyPortsAreSharedBetweenAllCallersAndReusableOnceReleased() {
|
||||
int first = service.reserveProxyPort();
|
||||
int second = service.reserveProxyPort();
|
||||
|
||||
assertEquals(7100, first);
|
||||
assertEquals(7101, second);
|
||||
assertFalse(service.reserveProxyPort(first), "a port already handed out cannot be reserved again");
|
||||
assertTrue(service.reserveProxyPort(7150), "a specific free port, such as a persisted one, can be reserved");
|
||||
assertEquals(7102, service.reserveProxyPort(), "reserving a specific port does not disturb the sequence");
|
||||
|
||||
service.releaseProxyPort(first);
|
||||
assertTrue(service.reserveProxyPort(first));
|
||||
assertFalse(service.reserveProxyPort(0), "port 0 is never a real port");
|
||||
}
|
||||
|
||||
@Test
|
||||
void advertisedEndpointUsesTheConfiguredHostAndTheGivenPort() {
|
||||
Endpoint endpoint = service.advertisedEndpoint(7123);
|
||||
|
||||
assertEquals("localhost", endpoint.getAddress());
|
||||
assertEquals(7123, endpoint.getPort());
|
||||
}
|
||||
}
|
||||
+81
-6
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -37,10 +38,12 @@ class RedshiftDataResourceResolverTest {
|
||||
return c;
|
||||
}
|
||||
|
||||
private final RedshiftServerlessService serverless = mock(RedshiftServerlessService.class);
|
||||
|
||||
private RedshiftDataResourceResolver resolver(RedshiftService redshift, SecretsManagerService secrets) {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
return new RedshiftDataResourceResolver(redshift, secrets, mapper, broker, regionResolver);
|
||||
return new RedshiftDataResourceResolver(redshift, secrets, mapper, broker, regionResolver, serverless);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,14 +66,86 @@ class RedshiftDataResourceResolverTest {
|
||||
assertEquals("Secret123", target.password());
|
||||
}
|
||||
|
||||
private static RedshiftServerlessService.WorkgroupTarget workgroupTarget() {
|
||||
return new RedshiftServerlessService.WorkgroupTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:" + ACCOUNT + ":workgroup/wg-id", "wg-1",
|
||||
"127.0.0.1", 55433, "analytics", "root", "Secret123", "root");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWorkgroupName() {
|
||||
void resolvesAWorkgroupAsTheNamespaceAdminWhenNoSecretIsGiven() {
|
||||
when(serverless.getWorkgroupTarget("wg-1", REGION)).thenReturn(workgroupTarget());
|
||||
ObjectNode req = mapper.createObjectNode();
|
||||
req.put("WorkgroupName", "wg-1");
|
||||
req.put("Database", "dev");
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> resolver(mock(RedshiftService.class), mock(SecretsManagerService.class)).resolve(req, REGION));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
req.put("Database", "analytics");
|
||||
|
||||
RedshiftDataResourceResolver.DatabaseTarget target =
|
||||
resolver(mock(RedshiftService.class), mock(SecretsManagerService.class)).resolve(req, REGION);
|
||||
|
||||
assertEquals("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT + ":workgroup/wg-id", target.arn());
|
||||
assertEquals("127.0.0.1", target.host());
|
||||
assertEquals(55433, target.port());
|
||||
assertEquals("analytics", target.database());
|
||||
assertEquals("root", target.user());
|
||||
assertEquals("Secret123", target.password());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupWithASecretConnectsWithTheSecretsCredentials() {
|
||||
when(serverless.getWorkgroupTarget("wg-1", REGION)).thenReturn(workgroupTarget());
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:" + ACCOUNT + ":secret:wg-creds";
|
||||
SecretVersion version = new SecretVersion();
|
||||
version.setSecretString("{\"username\":\"root\",\"password\":\"Secret123\"}");
|
||||
when(secrets.getSecretValue(eq(secretArn), any(), any(), eq(REGION))).thenReturn(version);
|
||||
ObjectNode req = mapper.createObjectNode();
|
||||
req.put("WorkgroupName", "wg-1");
|
||||
req.put("Database", "analytics");
|
||||
req.put("SecretArn", secretArn);
|
||||
|
||||
RedshiftDataResourceResolver.DatabaseTarget target =
|
||||
resolver(mock(RedshiftService.class), secrets).resolve(req, REGION);
|
||||
|
||||
assertEquals("root", target.user());
|
||||
assertEquals("Secret123", target.password());
|
||||
assertEquals(55433, target.port());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupRejectsAClusterIdentifierAndAWrongDatabase() {
|
||||
when(serverless.getWorkgroupTarget("wg-1", REGION)).thenReturn(workgroupTarget());
|
||||
RedshiftDataResourceResolver resolver = resolver(mock(RedshiftService.class), mock(SecretsManagerService.class));
|
||||
|
||||
ObjectNode both = mapper.createObjectNode();
|
||||
both.put("WorkgroupName", "wg-1");
|
||||
both.put("ClusterIdentifier", "wh");
|
||||
both.put("Database", "analytics");
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class, () -> resolver.resolve(both, REGION))
|
||||
.getErrorCode());
|
||||
|
||||
ObjectNode wrongDatabase = mapper.createObjectNode();
|
||||
wrongDatabase.put("WorkgroupName", "wg-1");
|
||||
wrongDatabase.put("Database", "dev");
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> resolver.resolve(wrongDatabase, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupStillRequiresADatabaseAndPropagatesAMissingWorkgroup() {
|
||||
when(serverless.getWorkgroupTarget("absent-wg", REGION))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "no such workgroup", 404));
|
||||
RedshiftDataResourceResolver resolver = resolver(mock(RedshiftService.class), mock(SecretsManagerService.class));
|
||||
|
||||
ObjectNode noDatabase = mapper.createObjectNode();
|
||||
noDatabase.put("WorkgroupName", "wg-1");
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> resolver.resolve(noDatabase, REGION)).getErrorCode());
|
||||
|
||||
ObjectNode absent = mapper.createObjectNode();
|
||||
absent.put("WorkgroupName", "absent-wg");
|
||||
absent.put("Database", "dev");
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> resolver.resolve(absent, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+45
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
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;
|
||||
@@ -62,6 +63,50 @@ class RedshiftDataServiceTest {
|
||||
return om.createObjectNode().put("Id", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupStatementNamesItsWorkgroupAndOmitsTheClusterIdentifier() {
|
||||
ObjectNode request = om.createObjectNode();
|
||||
request.put("Sql", "select 1");
|
||||
request.put("WorkgroupName", "wg-1");
|
||||
request.put("Database", "dev");
|
||||
|
||||
ObjectNode executed = service.executeStatement(request, REGION);
|
||||
|
||||
assertEquals("wg-1", executed.get("WorkgroupName").asText());
|
||||
assertFalse(executed.has("ClusterIdentifier"),
|
||||
"AWS does not return ClusterIdentifier when connecting to a serverless workgroup");
|
||||
ObjectNode described = service.describeStatement(idOf(executed.get("Id").asText()));
|
||||
assertEquals("wg-1", described.get("WorkgroupName").asText());
|
||||
assertFalse(described.has("ClusterIdentifier"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterStatementKeepsItsNullWorkgroupName() {
|
||||
ObjectNode executed = service.executeStatement(req("select 1"), REGION);
|
||||
|
||||
assertEquals("wh", executed.get("ClusterIdentifier").asText());
|
||||
assertTrue(executed.get("WorkgroupName").isNull());
|
||||
ObjectNode described = service.describeStatement(idOf(executed.get("Id").asText()));
|
||||
assertEquals("wh", described.get("ClusterIdentifier").asText());
|
||||
assertTrue(described.get("WorkgroupName").isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupBatchPassesItsWorkgroupToEverySubStatement() {
|
||||
ObjectNode request = om.createObjectNode();
|
||||
request.putArray("Sqls").add("select 1").add("select 2");
|
||||
request.put("WorkgroupName", "wg-1");
|
||||
request.put("Database", "dev");
|
||||
|
||||
ObjectNode executed = service.batchExecuteStatement(request, REGION);
|
||||
|
||||
ObjectNode described = service.describeStatement(idOf(executed.get("Id").asText()));
|
||||
assertEquals("wg-1", described.get("WorkgroupName").asText());
|
||||
for (JsonNode sub : described.get("SubStatements")) {
|
||||
assertFalse(sub.has("ClusterIdentifier"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages checked against a real Redshift cluster on 2026-09-13.
|
||||
*/
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessEndpointsTest {
|
||||
|
||||
private final RedshiftService redshift = mock(RedshiftService.class);
|
||||
private final RedshiftServerlessEndpoints endpoints = new RedshiftServerlessEndpoints(redshift);
|
||||
|
||||
@Test
|
||||
void allocateReservesAPortFromTheSharedPoolAndAdvertisesIt() {
|
||||
when(redshift.reserveProxyPort()).thenReturn(7101);
|
||||
when(redshift.advertisedEndpoint(7101)).thenReturn(new Endpoint("localhost", 7101));
|
||||
|
||||
Endpoint allocated = endpoints.allocate();
|
||||
|
||||
assertEquals("localhost", allocated.getAddress());
|
||||
assertEquals(7101, allocated.getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreKeepsThePersistedPortAndRebuildsTheAddressFromCurrentConfiguration() {
|
||||
when(redshift.reserveProxyPort(7105)).thenReturn(true);
|
||||
when(redshift.advertisedEndpoint(7105)).thenReturn(new Endpoint("new-host", 7105));
|
||||
|
||||
Endpoint restored = endpoints.restore(new Endpoint("old-host", 7105));
|
||||
|
||||
assertEquals("new-host", restored.getAddress());
|
||||
assertEquals(7105, restored.getPort());
|
||||
verify(redshift, never()).reserveProxyPort();
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreAllocatesAFreshEndpointWhenThePersistedPortIsTaken() {
|
||||
when(redshift.reserveProxyPort(7105)).thenReturn(false);
|
||||
when(redshift.reserveProxyPort()).thenReturn(7110);
|
||||
when(redshift.advertisedEndpoint(7110)).thenReturn(new Endpoint("localhost", 7110));
|
||||
|
||||
assertEquals(7110, endpoints.restore(new Endpoint("localhost", 7105)).getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreOfAWorkgroupWithNoEndpointAllocatesOne() {
|
||||
when(redshift.reserveProxyPort()).thenReturn(7111);
|
||||
when(redshift.advertisedEndpoint(7111)).thenReturn(new Endpoint("localhost", 7111));
|
||||
|
||||
assertEquals(7111, endpoints.restore(null).getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseReturnsThePortAndToleratesNull() {
|
||||
endpoints.release(new Endpoint("localhost", 7120));
|
||||
endpoints.release(null);
|
||||
|
||||
verify(redshift).releaseProxyPort(7120);
|
||||
}
|
||||
}
|
||||
+118
@@ -1,15 +1,23 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftServerlessIntegrationTest {
|
||||
@@ -24,6 +32,22 @@ class RedshiftServerlessIntegrationTest {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* The metadata behaviour under test needs no PostgreSQL container, so the runtime is replaced:
|
||||
* these tests then run without Docker, and the real container and proxy are exercised by
|
||||
* {@code RedshiftServerlessRuntimeIntegrationTest}.
|
||||
*/
|
||||
@InjectMock
|
||||
RedshiftServerlessRuntime runtime;
|
||||
|
||||
@BeforeEach
|
||||
void stubRuntime() {
|
||||
when(runtime.generatePassword()).thenReturn("Generated123");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAppliesAwsDefaultsAndNeverReturnsTheAdminPassword() {
|
||||
call("CreateNamespace", """
|
||||
@@ -163,6 +187,100 @@ class RedshiftServerlessIntegrationTest {
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupLifecycleIsVisibleThroughSeparateReads() {
|
||||
call("CreateNamespace", "{\"namespaceName\":\"wg-life-ns\",\"adminUsername\":\"admin\"}").statusCode(200);
|
||||
|
||||
call("CreateWorkgroup", """
|
||||
{"workgroupName":"wg-life","namespaceName":"wg-life-ns","baseCapacity":32,
|
||||
"publiclyAccessible":true,"tags":[{"key":"env","value":"dev"}]}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("workgroup.workgroupName", equalTo("wg-life"))
|
||||
.body("workgroup.namespaceName", equalTo("wg-life-ns"))
|
||||
.body("workgroup.status", equalTo("AVAILABLE"))
|
||||
.body("workgroup.baseCapacity", equalTo(32))
|
||||
.body("workgroup.port", equalTo(5439))
|
||||
.body("workgroup.trackName", equalTo("current"))
|
||||
.body("workgroup.pricePerformanceTarget.status", equalTo("DISABLED"))
|
||||
.body("workgroup.endpoint.address", notNullValue())
|
||||
.body("workgroup.endpoint.port", greaterThan(0))
|
||||
.body("workgroup.workgroupArn", matchesPattern(
|
||||
"arn:aws:redshift-serverless:us-east-1:\\d{12}:workgroup/"
|
||||
+ "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))
|
||||
.body("workgroup.creationDate", matchesPattern(
|
||||
"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"));
|
||||
|
||||
call("GetWorkgroup", "{\"workgroupName\":\"wg-life\"}")
|
||||
.statusCode(200)
|
||||
.body("workgroup.publiclyAccessible", equalTo(true));
|
||||
|
||||
call("ListWorkgroups", "{}")
|
||||
.statusCode(200)
|
||||
.body("workgroups.workgroupName", hasItem("wg-life"));
|
||||
|
||||
call("UpdateWorkgroup", "{\"workgroupName\":\"wg-life\",\"baseCapacity\":64,\"trackName\":\"trailing\"}")
|
||||
.statusCode(200)
|
||||
.body("workgroup.baseCapacity", equalTo(64))
|
||||
.body("workgroup.trackName", equalTo("current"))
|
||||
.body("workgroup.pendingTrackName", equalTo("trailing"));
|
||||
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"wg-life-ns\"}")
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"));
|
||||
|
||||
call("DeleteWorkgroup", "{\"workgroupName\":\"wg-life\"}")
|
||||
.statusCode(200)
|
||||
.body("workgroup.status", equalTo("DELETING"));
|
||||
call("GetWorkgroup", "{\"workgroupName\":\"wg-life\"}")
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"wg-life-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupTagsAreEditableThroughTheWorkgroupArn() {
|
||||
call("CreateNamespace", "{\"namespaceName\":\"wg-tag-ns\",\"adminUsername\":\"admin\"}").statusCode(200);
|
||||
String arn = call("CreateWorkgroup", """
|
||||
{"workgroupName":"wg-tag","namespaceName":"wg-tag-ns","tags":[{"key":"env","value":"dev"}]}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("workgroup.workgroupArn");
|
||||
|
||||
call("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"team\",\"value\":\"data\"}]}")
|
||||
.statusCode(200);
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("tags.key", hasItem("env"))
|
||||
.body("tags.key", hasItem("team"));
|
||||
call("UntagResource", "{\"resourceArn\":\"" + arn + "\",\"tagKeys\":[\"env\"]}").statusCode(200);
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("tags.size()", equalTo(1));
|
||||
|
||||
call("DeleteWorkgroup", "{\"workgroupName\":\"wg-tag\"}").statusCode(200);
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"wg-tag-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupCreateRejectsAnUnknownNamespaceADuplicateAndABadPort() {
|
||||
call("CreateWorkgroup", "{\"workgroupName\":\"wg-orphan\",\"namespaceName\":\"absent-ns\"}")
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
call("CreateNamespace", "{\"namespaceName\":\"wg-err-ns\",\"adminUsername\":\"admin\"}").statusCode(200);
|
||||
call("CreateWorkgroup", "{\"workgroupName\":\"wg-err\",\"namespaceName\":\"wg-err-ns\",\"port\":5000}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
call("CreateWorkgroup", "{\"workgroupName\":\"wg-err\",\"namespaceName\":\"wg-err-ns\"}").statusCode(200);
|
||||
call("CreateWorkgroup", "{\"workgroupName\":\"wg-err\",\"namespaceName\":\"wg-err-ns\"}")
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"));
|
||||
|
||||
call("DeleteWorkgroup", "{\"workgroupName\":\"wg-err\"}").statusCode(200);
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"wg-err-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
|
||||
+173
-2
@@ -7,18 +7,25 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftIamDbUserResolver;
|
||||
import io.github.hectorvent.floci.services.redshift.TempCredential;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Workgroup;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -37,6 +44,7 @@ class RedshiftServerlessJsonHandlerTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private RedshiftServerlessJsonHandler handler;
|
||||
private RedshiftIamDbUserResolver iamDbUserResolver;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@@ -51,8 +59,171 @@ class RedshiftServerlessJsonHandlerTest {
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
|
||||
+ invocation.getArgument(2, String.class));
|
||||
AccountAwareStorageBackend<Workgroup> workgroupStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-workgroups.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) workgroupStore);
|
||||
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
|
||||
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
|
||||
RedshiftServerlessRuntime runtime = mock(RedshiftServerlessRuntime.class);
|
||||
when(runtime.generatePassword()).thenReturn("Generated123");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
|
||||
when(runtime.issueCredential(any(), any(), any(), any(), anyInt())).thenAnswer(invocation ->
|
||||
new TempCredential(invocation.getArgument(3), "tempPassword1",
|
||||
Instant.ofEpochSecond(1_800_000_000L), List.of()));
|
||||
iamDbUserResolver = mock(RedshiftIamDbUserResolver.class);
|
||||
when(iamDbUserResolver.resolveDbUser("AUTH")).thenReturn("IAM:alice");
|
||||
handler = new RedshiftServerlessJsonHandler(
|
||||
new RedshiftServerlessService(storageFactory, regionResolver), mapper);
|
||||
new RedshiftServerlessService(storageFactory, regionResolver, endpoints, runtime), mapper,
|
||||
iamDbUserResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupTimestampIsAnIso8601StringAndTheShapeFollowsTheApiModel() {
|
||||
create("shape-ns");
|
||||
|
||||
JsonNode workgroup = body(handler.handle("CreateWorkgroup", parse("""
|
||||
{"workgroupName":"shape-wg","namespaceName":"shape-ns","baseCapacity":32,"maxCapacity":64,
|
||||
"configParameters":[{"parameterKey":"datestyle","parameterValue":"ISO, MDY"}],
|
||||
"securityGroupIds":["sg-1"],"subnetIds":["subnet-1"],
|
||||
"pricePerformanceTarget":{"status":"ENABLED","level":50},
|
||||
"tags":[{"key":"env","value":"dev"}]}
|
||||
"""), REGION)).get("workgroup");
|
||||
|
||||
assertTrue(workgroup.get("creationDate").isTextual());
|
||||
assertTrue(workgroup.get("creationDate").textValue()
|
||||
.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"));
|
||||
assertEquals("shape-wg", workgroup.get("workgroupName").textValue());
|
||||
assertEquals("shape-ns", workgroup.get("namespaceName").textValue());
|
||||
assertEquals("AVAILABLE", workgroup.get("status").textValue());
|
||||
assertEquals(32, workgroup.get("baseCapacity").intValue());
|
||||
assertEquals(64, workgroup.get("maxCapacity").intValue());
|
||||
assertEquals(5439, workgroup.get("port").intValue());
|
||||
assertEquals("localhost", workgroup.get("endpoint").get("address").textValue());
|
||||
assertEquals(7100, workgroup.get("endpoint").get("port").intValue());
|
||||
assertEquals("datestyle", workgroup.get("configParameters").get(0).get("parameterKey").textValue());
|
||||
assertEquals("sg-1", workgroup.get("securityGroupIds").get(0).textValue());
|
||||
assertEquals(50, workgroup.get("pricePerformanceTarget").get("level").intValue());
|
||||
assertEquals("ENABLED", workgroup.get("pricePerformanceTarget").get("status").textValue());
|
||||
assertTrue(workgroup.get("workgroupArn").textValue().contains(":workgroup/"));
|
||||
assertFalse(workgroup.has("pendingTrackName"));
|
||||
assertFalse(workgroup.has("workgroupVersion"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCredentialsReturnsEpochSecondNumbersAndTheCallersDatabaseUser() {
|
||||
create("cred-shape-ns");
|
||||
body(handler.handle("CreateWorkgroup",
|
||||
parse("{\"workgroupName\":\"cred-shape-wg\",\"namespaceName\":\"cred-shape-ns\"}"), REGION));
|
||||
|
||||
JsonNode credentials = body(handler.handle("GetCredentials",
|
||||
parse("{\"workgroupName\":\"cred-shape-wg\",\"dbName\":\"dev\",\"durationSeconds\":1800}"),
|
||||
REGION, "AUTH"));
|
||||
|
||||
assertEquals("IAM:alice", credentials.get("dbUser").textValue());
|
||||
assertEquals("tempPassword1", credentials.get("dbPassword").textValue());
|
||||
assertTrue(credentials.get("expiration").isNumber(),
|
||||
"expiration has no timestamp trait, so it is epoch seconds as a JSON number");
|
||||
assertEquals(1_800_000_000L, credentials.get("expiration").longValue());
|
||||
assertEquals(1_800_000_000L, credentials.get("nextRefreshTime").longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCredentialsRejectsABadDurationAMissingWorkgroupAndACustomDomain() {
|
||||
create("cred-err-ns");
|
||||
body(handler.handle("CreateWorkgroup",
|
||||
parse("{\"workgroupName\":\"cred-err-wg\",\"namespaceName\":\"cred-err-ns\"}"), REGION));
|
||||
|
||||
Response tooShort = handler.handle("GetCredentials",
|
||||
parse("{\"workgroupName\":\"cred-err-wg\",\"durationSeconds\":60}"), REGION, "AUTH");
|
||||
assertEquals(400, tooShort.getStatus());
|
||||
assertEquals("ValidationException", errorType(tooShort));
|
||||
|
||||
Response wrongType = handler.handle("GetCredentials",
|
||||
parse("{\"workgroupName\":\"cred-err-wg\",\"durationSeconds\":\"900\"}"), REGION, "AUTH");
|
||||
assertEquals(400, wrongType.getStatus());
|
||||
|
||||
Response missing = handler.handle("GetCredentials", parse("{\"workgroupName\":\"absent-wg\"}"), REGION, "AUTH");
|
||||
assertEquals(404, missing.getStatus());
|
||||
assertEquals("ResourceNotFoundException", errorType(missing));
|
||||
|
||||
Response customDomain = handler.handle("GetCredentials",
|
||||
parse("{\"customDomainName\":\"wg.example.com\"}"), REGION, "AUTH");
|
||||
assertEquals(400, customDomain.getStatus());
|
||||
assertEquals("ValidationException", errorType(customDomain));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminPasswordIsAcceptedOnCreateAndUpdateAndNeverReturned() {
|
||||
JsonNode created = body(handler.handle("CreateNamespace",
|
||||
parse("{\"namespaceName\":\"pw-shape-ns\",\"adminUsername\":\"root\",\"adminUserPassword\":\"Secret123\"}"),
|
||||
REGION)).get("namespace");
|
||||
assertFalse(created.has("adminUserPassword"));
|
||||
|
||||
JsonNode updated = body(handler.handle("UpdateNamespace",
|
||||
parse("{\"namespaceName\":\"pw-shape-ns\",\"adminUserPassword\":\"Changed123\"}"), REGION))
|
||||
.get("namespace");
|
||||
assertFalse(updated.has("adminUserPassword"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listWorkgroupsReturnsTheWorkgroupsMember() {
|
||||
create("list-shape-ns");
|
||||
body(handler.handle("CreateWorkgroup",
|
||||
parse("{\"workgroupName\":\"list-shape-wg\",\"namespaceName\":\"list-shape-ns\"}"), REGION));
|
||||
|
||||
JsonNode listed = body(handler.handle("ListWorkgroups", mapper.createObjectNode(), REGION));
|
||||
|
||||
assertEquals("list-shape-wg", listed.get("workgroups").get(0).get("workgroupName").textValue());
|
||||
assertFalse(listed.has("nextToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongTypedWorkgroupMembersAreRejected() {
|
||||
create("typed-ns");
|
||||
for (String member : new String[] {
|
||||
"\"baseCapacity\":\"32\"", "\"baseCapacity\":3.5", "\"port\":\"5439\"",
|
||||
"\"publiclyAccessible\":\"true\"", "\"enhancedVpcRouting\":1",
|
||||
"\"configParameters\":\"datestyle\"", "\"configParameters\":[\"datestyle\"]",
|
||||
"\"pricePerformanceTarget\":\"ENABLED\"", "\"securityGroupIds\":\"sg-1\"",
|
||||
"\"subnetIds\":[7]", "\"tags\":\"env=dev\""}) {
|
||||
Response response = handler.handle("CreateWorkgroup", parse(
|
||||
"{\"workgroupName\":\"typed-wg\",\"namespaceName\":\"typed-ns\"," + member + "}"), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus(), member + " must be rejected");
|
||||
assertEquals("ValidationException", errorType(response), member);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorkgroupKeepsOmittedMembersAndReportsAPendingTrack() {
|
||||
create("upd-shape-ns");
|
||||
body(handler.handle("CreateWorkgroup",
|
||||
parse("{\"workgroupName\":\"upd-shape-wg\",\"namespaceName\":\"upd-shape-ns\",\"baseCapacity\":32}"),
|
||||
REGION));
|
||||
|
||||
JsonNode updated = body(handler.handle("UpdateWorkgroup",
|
||||
parse("{\"workgroupName\":\"upd-shape-wg\",\"trackName\":\"trailing\"}"), REGION)).get("workgroup");
|
||||
|
||||
assertEquals(32, updated.get("baseCapacity").intValue());
|
||||
assertEquals("current", updated.get("trackName").textValue());
|
||||
assertEquals("trailing", updated.get("pendingTrackName").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWorkgroupReturnsTheDeletedWorkgroupInTheDeletingState() {
|
||||
create("del-shape-ns");
|
||||
body(handler.handle("CreateWorkgroup",
|
||||
parse("{\"workgroupName\":\"del-shape-wg\",\"namespaceName\":\"del-shape-ns\"}"), REGION));
|
||||
|
||||
JsonNode deleted = body(handler.handle("DeleteWorkgroup",
|
||||
request("workgroupName", "del-shape-wg"), REGION)).get("workgroup");
|
||||
|
||||
assertEquals("DELETING", deleted.get("status").textValue());
|
||||
Response missing = handler.handle("GetWorkgroup", request("workgroupName", "del-shape-wg"), REGION);
|
||||
assertEquals(404, missing.getStatus());
|
||||
assertEquals("ResourceNotFoundException", errorType(missing));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,7 +287,7 @@ class RedshiftServerlessJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void anUnknownActionIsReportedAsUnknownOperation() {
|
||||
Response response = handler.handle("CreateWorkgroup", mapper.createObjectNode(), REGION);
|
||||
Response response = handler.handle("CreateSnapshot", mapper.createObjectNode(), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("UnknownOperationException", errorType(response));
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Runs a real workgroup: the PostgreSQL container, the auth proxy on the advertised endpoint, the
|
||||
* Redshift Data API addressed by {@code WorkgroupName}, and {@code GetCredentials}. Needs Docker.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class RedshiftServerlessRuntimeIntegrationTest {
|
||||
|
||||
private static final String NAMESPACE = "rt-it-ns";
|
||||
private static final String WORKGROUP = "rt-it-wg";
|
||||
private static final String ADMIN_PASSWORD = "Secret123";
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
RedshiftServerlessService service;
|
||||
|
||||
private int endpointPort;
|
||||
private String workgroupArn;
|
||||
private boolean created;
|
||||
|
||||
/**
|
||||
* Runs before each test but creates the workgroup once: Quarkus points RestAssured at the test
|
||||
* server in its own per-test callback, so a {@code @BeforeAll} would still see the default port.
|
||||
*/
|
||||
@BeforeEach
|
||||
void ensureWorkgroup() {
|
||||
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for Redshift Serverless runtime tests");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
if (created) {
|
||||
return;
|
||||
}
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """
|
||||
{"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"%s","dbName":"dev"}
|
||||
""".formatted(NAMESPACE, ADMIN_PASSWORD)).then().statusCode(200);
|
||||
created = true;
|
||||
ExtractableResponse<Response> workgroup = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateWorkgroup", """
|
||||
{"workgroupName":"%s","namespaceName":"%s"}
|
||||
""".formatted(WORKGROUP, NAMESPACE)).then().statusCode(200).extract();
|
||||
endpointPort = workgroup.path("workgroup.endpoint.port");
|
||||
workgroupArn = workgroup.path("workgroup.workgroupArn");
|
||||
}
|
||||
|
||||
/** Through the service: Quarkus has already pointed RestAssured away from the test server by now. */
|
||||
@AfterAll
|
||||
void deleteWorkgroup() {
|
||||
if (created) {
|
||||
service.deleteWorkgroup(WORKGROUP, REGION);
|
||||
service.deleteNamespace(NAMESPACE, REGION);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean dockerAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
|
||||
.redirectErrorStream(true).start();
|
||||
return p.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String jdbcUrl() {
|
||||
// 127.0.0.1 rather than the advertised address: CI sets floci.emulator.hostname to a name
|
||||
// that does not resolve from the test JVM.
|
||||
return "jdbc:postgresql://127.0.0.1:" + endpointPort + "/dev";
|
||||
}
|
||||
|
||||
private Connection connect(String user, String password) throws SQLException {
|
||||
return Awaitility.await()
|
||||
.atMost(Duration.ofSeconds(30))
|
||||
.pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500))
|
||||
.ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(jdbcUrl(), user, password), Objects::nonNull);
|
||||
}
|
||||
|
||||
private String executeAndWait(String sql) {
|
||||
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql": "%s", "WorkgroupName": "%s", "Database": "dev"}
|
||||
""".formatted(sql, WORKGROUP)).then().statusCode(200)
|
||||
.extract().path("Id");
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(250)).until(() -> {
|
||||
String status = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status");
|
||||
assertFalse("FAILED".equals(status) || "ABORTED".equals(status),
|
||||
() -> "statement " + id + " ended " + status);
|
||||
return "FINISHED".equals(status);
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdvertisedEndpointAcceptsTheNamespaceAdminAndRefusesAWrongPassword() throws SQLException {
|
||||
try (Connection connection = connect("admin", ADMIN_PASSWORD);
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("select 1")) {
|
||||
assertTrue(result.next());
|
||||
assertEquals(1, result.getInt(1));
|
||||
}
|
||||
|
||||
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl(), "admin", "wrong-password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDataApiRunsStatementsAgainstTheWorkgroupByNameAndByArn() throws SQLException {
|
||||
String createId = executeAndWait("CREATE TABLE sl_people (id int, name varchar(20))");
|
||||
executeAndWait("INSERT INTO sl_people VALUES (1, 'a'), (2, 'b')");
|
||||
String selectId = executeAndWait("SELECT id, name FROM sl_people ORDER BY id");
|
||||
|
||||
ExtractableResponse<Response> described = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + selectId + "\"}").then().statusCode(200).extract();
|
||||
assertEquals(WORKGROUP, described.path("WorkgroupName"));
|
||||
assertNull(described.path("ClusterIdentifier"));
|
||||
assertNotNull(createId);
|
||||
|
||||
ExtractableResponse<Response> result = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
|
||||
"{\"Id\":\"" + selectId + "\"}").then().statusCode(200).extract();
|
||||
assertEquals(2, ((Number) result.path("TotalNumRows")).intValue());
|
||||
assertEquals("a", result.path("Records[0][1].stringValue"));
|
||||
|
||||
// The same table is visible through the endpoint, and the workgroup ARN addresses the workgroup too.
|
||||
try (Connection connection = connect("admin", ADMIN_PASSWORD);
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery("select count(*) from sl_people")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(2, rows.getInt(1));
|
||||
}
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql": "select 1", "WorkgroupName": "%s", "Database": "dev"}
|
||||
""".formatted(workgroupArn)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDataApiRejectsAWrongDatabaseAndBothIdentifiers() {
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql": "select 1", "WorkgroupName": "%s", "Database": "other"}
|
||||
""".formatted(WORKGROUP)).then().statusCode(400);
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql": "select 1", "WorkgroupName": "%s", "ClusterIdentifier": "wh", "Database": "dev"}
|
||||
""".formatted(WORKGROUP)).then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCredentialsMintsAPasswordTheEndpointAccepts() throws SQLException {
|
||||
ExtractableResponse<Response> credentials = RestAssuredJsonUtils.awsAction("RedshiftServerless", "GetCredentials",
|
||||
"{\"workgroupName\":\"" + WORKGROUP + "\",\"dbName\":\"dev\"}").then().statusCode(200).extract();
|
||||
String dbUser = credentials.path("dbUser");
|
||||
String dbPassword = credentials.path("dbPassword");
|
||||
assertNotNull(dbUser);
|
||||
assertNotNull(dbPassword);
|
||||
|
||||
try (Connection connection = connect(dbUser, dbPassword)) {
|
||||
assertTrue(connection.isValid(5));
|
||||
}
|
||||
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl(), dbUser, "stale-password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAdminPasswordChangeAppliesToNewConnections() throws SQLException {
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "UpdateNamespace",
|
||||
"{\"namespaceName\":\"" + NAMESPACE + "\",\"adminUserPassword\":\"Rotated123\"}")
|
||||
.then().statusCode(200);
|
||||
try {
|
||||
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl(), "admin", ADMIN_PASSWORD));
|
||||
try (Connection connection = connect("admin", "Rotated123")) {
|
||||
assertTrue(connection.isValid(5));
|
||||
}
|
||||
} finally {
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "UpdateNamespace",
|
||||
"{\"namespaceName\":\"" + NAMESPACE + "\",\"adminUserPassword\":\"" + ADMIN_PASSWORD + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheWorkgroupClosesItsEndpoint() {
|
||||
String namespace = "rt-it-del-ns";
|
||||
String workgroup = "rt-it-del-wg";
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """
|
||||
{"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"%s"}
|
||||
""".formatted(namespace, ADMIN_PASSWORD)).then().statusCode(200);
|
||||
int port = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateWorkgroup", """
|
||||
{"workgroupName":"%s","namespaceName":"%s"}
|
||||
""".formatted(workgroup, namespace)).then().statusCode(200).extract().path("workgroup.endpoint.port");
|
||||
try {
|
||||
assertTrue(isListening(port), "the endpoint must be live once the workgroup is created");
|
||||
} finally {
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "DeleteWorkgroup",
|
||||
"{\"workgroupName\":\"" + workgroup + "\"}").then().statusCode(200);
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "DeleteNamespace",
|
||||
"{\"namespaceName\":\"" + namespace + "\"}").then().statusCode(200);
|
||||
}
|
||||
assertFalse(isListening(port), "the endpoint must be closed once the workgroup is deleted");
|
||||
}
|
||||
|
||||
private static boolean isListening(int port) {
|
||||
try (Socket socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress("127.0.0.1", port), 1000);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
|
||||
import io.github.hectorvent.floci.services.redshift.TempCredential;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessRuntimeTest {
|
||||
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String BACKEND_ID = "serverless_us-east-1_my-wg";
|
||||
private static final String RELAY_KEY = ACCOUNT + ":" + BACKEND_ID;
|
||||
private static final Endpoint ENDPOINT = new Endpoint("localhost", 7100);
|
||||
|
||||
private final RedshiftContainerManager containers = mock(RedshiftContainerManager.class);
|
||||
private final RedshiftProxyManager proxies = mock(RedshiftProxyManager.class);
|
||||
private final RedshiftCredentialBroker broker = new RedshiftCredentialBroker();
|
||||
private final RedshiftServerlessRuntime runtime = new RedshiftServerlessRuntime(containers, proxies, broker);
|
||||
|
||||
private static RedshiftContainerHandle handle() {
|
||||
return new RedshiftContainerHandle("container-id", BACKEND_ID, "172.17.0.5", 5432);
|
||||
}
|
||||
|
||||
private PasswordValidator startAndCaptureValidator(RedshiftServerlessRuntime.AdminCredentials admin) {
|
||||
when(containers.start(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
|
||||
runtime.start(ACCOUNT, REGION, "my-wg", "root", "Secret123", "analytics", ENDPOINT, false,
|
||||
() -> Optional.ofNullable(admin));
|
||||
ArgumentCaptor<PasswordValidator> validator = ArgumentCaptor.forClass(PasswordValidator.class);
|
||||
verify(proxies).startProxy(eq(RELAY_KEY), eq(7100), eq("172.17.0.5"), eq(5432), eq("localhost"),
|
||||
eq("root"), eq("Secret123"), eq("analytics"), validator.capture(), eq(List.of()));
|
||||
return validator.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startRunsTheContainerThenFrontsItWithTheProxyOnTheAllocatedEndpoint() {
|
||||
when(containers.start(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
|
||||
|
||||
RedshiftServerlessRuntime.Backend backend = runtime.start(ACCOUNT, REGION, "my-wg", "root", "Secret123",
|
||||
"analytics", ENDPOINT, false, Optional::empty);
|
||||
|
||||
assertEquals(new RedshiftServerlessRuntime.Backend("172.17.0.5", 5432), backend);
|
||||
InOrder order = inOrder(containers, proxies);
|
||||
order.verify(containers).start(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics");
|
||||
order.verify(proxies).startProxy(eq(RELAY_KEY), eq(7100), eq("172.17.0.5"), eq(5432), eq("localhost"),
|
||||
eq("root"), eq("Secret123"), eq("analytics"), any(PasswordValidator.class), eq(List.of()));
|
||||
verify(containers, never()).adoptOrStart(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptReattachesToASurvivingContainer() {
|
||||
when(containers.adoptOrStart(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
|
||||
|
||||
runtime.start(ACCOUNT, REGION, "my-wg", "root", "Secret123", "analytics", ENDPOINT, true, Optional::empty);
|
||||
|
||||
verify(containers, never()).start(any(), any(), any(), any(), any());
|
||||
verify(proxies).startProxy(eq(RELAY_KEY), eq(7100), any(), anyInt(), any(), any(), any(), any(),
|
||||
any(PasswordValidator.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProxyThatFailsToStartRollsBackTheContainerAndCredentials() {
|
||||
when(containers.start(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
|
||||
doThrow(new RuntimeException("port in use")).when(proxies).startProxy(any(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(PasswordValidator.class), any());
|
||||
broker.issue(ACCOUNT, BACKEND_ID, "IAM:alice", List.of(), 900);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> runtime.start(ACCOUNT, REGION, "my-wg", "root", "Secret123",
|
||||
"analytics", ENDPOINT, false, Optional::empty));
|
||||
|
||||
verify(proxies).stopProxy(RELAY_KEY);
|
||||
verify(containers).stop(ACCOUNT, BACKEND_ID);
|
||||
assertTrue(broker.resolve(ACCOUNT, BACKEND_ID, "IAM:alice").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopClosesTheProxyBeforeRemovingTheContainerAndRevokesCredentials() {
|
||||
broker.issue(ACCOUNT, BACKEND_ID, "IAM:alice", List.of(), 900);
|
||||
|
||||
runtime.stop(ACCOUNT, REGION, "my-wg");
|
||||
|
||||
InOrder order = inOrder(proxies, containers);
|
||||
order.verify(proxies).stopProxy(RELAY_KEY);
|
||||
order.verify(containers).stop(ACCOUNT, BACKEND_ID);
|
||||
assertTrue(broker.resolve(ACCOUNT, BACKEND_ID, "IAM:alice").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProxyThatCannotBeClosedStopsTheStopBeforeTheContainerIsTouched() {
|
||||
doThrow(new RuntimeException("listener still bound")).when(proxies).stopProxy(RELAY_KEY);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> runtime.stop(ACCOUNT, REGION, "my-wg"));
|
||||
|
||||
verify(containers, never()).stop(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeMasterPasswordUpdatesTheRoleAndTheProxyBackendLeg() {
|
||||
runtime.changeMasterPassword(ACCOUNT, REGION, "my-wg", "root", "analytics", "Secret123", "Changed123");
|
||||
|
||||
verify(containers).alterUserPassword(ACCOUNT, BACKEND_ID, "root", "Changed123", "analytics");
|
||||
verify(proxies).updateMasterPassword(RELAY_KEY, "Changed123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProxyUpdateThatFailsPutsTheRolePasswordBack() {
|
||||
doThrow(new RuntimeException("proxy gone")).when(proxies).updateMasterPassword(RELAY_KEY, "Changed123");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> runtime.changeMasterPassword(
|
||||
ACCOUNT, REGION, "my-wg", "root", "analytics", "Secret123", "Changed123"));
|
||||
|
||||
verify(containers).alterUserPassword(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedRollbackKeepsTheOriginalProxyFailureAsTheThrownError() {
|
||||
RuntimeException proxyFailure = new RuntimeException("proxy gone");
|
||||
doThrow(proxyFailure).when(proxies).updateMasterPassword(RELAY_KEY, "Changed123");
|
||||
doThrow(new RuntimeException("psql failed")).when(containers)
|
||||
.alterUserPassword(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics");
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () -> runtime.changeMasterPassword(
|
||||
ACCOUNT, REGION, "my-wg", "root", "analytics", "Secret123", "Changed123"));
|
||||
|
||||
assertEquals(proxyFailure, thrown);
|
||||
assertEquals(1, thrown.getSuppressed().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreMasterPasswordLeavesTheProxyAloneWhenTheRoleCannotBeRestored() {
|
||||
doThrow(new RuntimeException("psql failed")).when(containers)
|
||||
.alterUserPassword(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics");
|
||||
|
||||
assertThrows(RuntimeException.class,
|
||||
() -> runtime.restoreMasterPassword(ACCOUNT, REGION, "my-wg", "root", "analytics", "Secret123"));
|
||||
|
||||
verify(proxies, never()).updateMasterPassword(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreMasterPasswordResetsTheRoleAndTheProxy() {
|
||||
runtime.restoreMasterPassword(ACCOUNT, REGION, "my-wg", "root", "analytics", "Secret123");
|
||||
|
||||
verify(containers).alterUserPassword(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics");
|
||||
verify(proxies).updateMasterPassword(RELAY_KEY, "Secret123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminPairIsMasterEquivalentAndAWrongAdminPasswordIsRejected() {
|
||||
PasswordValidator validator = startAndCaptureValidator(
|
||||
new RedshiftServerlessRuntime.AdminCredentials("root", "Secret123"));
|
||||
|
||||
assertEquals(PasswordValidator.AuthResult.MASTER_EQUIVALENT, validator.validate("root", "Secret123"));
|
||||
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("root", "wrong"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLiveGetCredentialsPasswordIsMasterEquivalentAndAStaleOneForThatUserIsRejected() {
|
||||
PasswordValidator validator = startAndCaptureValidator(
|
||||
new RedshiftServerlessRuntime.AdminCredentials("root", "Secret123"));
|
||||
|
||||
TempCredential credential = runtime.issueCredential(ACCOUNT, REGION, "my-wg", "IAM:alice", 900);
|
||||
|
||||
assertEquals(PasswordValidator.AuthResult.MASTER_EQUIVALENT,
|
||||
validator.validate("IAM:alice", credential.password()));
|
||||
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("IAM:alice", "stale"));
|
||||
assertEquals(PasswordValidator.AuthResult.PASSTHROUGH, validator.validate("someone-else", "pw"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceThatIsGoneVouchesForNothing() {
|
||||
PasswordValidator validator = startAndCaptureValidator(null);
|
||||
TempCredential credential = runtime.issueCredential(ACCOUNT, REGION, "my-wg", "IAM:alice", 900);
|
||||
|
||||
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("root", "Secret123"));
|
||||
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("IAM:alice", credential.password()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBackendIdCannotCollideWithAClusterIdentifier() {
|
||||
assertEquals(BACKEND_ID, RedshiftServerlessRuntime.backendId(REGION, "my-wg"));
|
||||
assertTrue(BACKEND_ID.contains("_"), "cluster identifiers cannot contain an underscore");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedPasswordsAreLongAlphanumericAndDifferEachTime() {
|
||||
String first = runtime.generatePassword();
|
||||
String second = runtime.generatePassword();
|
||||
|
||||
assertEquals(32, first.length());
|
||||
assertTrue(first.matches("[A-Za-z0-9]+"), first);
|
||||
assertNotEquals(first, second);
|
||||
}
|
||||
}
|
||||
+506
-1
@@ -6,23 +6,37 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.TempCredential;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.PricePerformanceTarget;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Workgroup;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -33,6 +47,10 @@ class RedshiftServerlessServiceTest {
|
||||
|
||||
private RedshiftServerlessService service;
|
||||
private AccountAwareStorageBackend<Namespace> store;
|
||||
private AccountAwareStorageBackend<Workgroup> workgroupStore;
|
||||
private RedshiftServerlessEndpoints endpoints;
|
||||
private RedshiftServerlessRuntime runtime;
|
||||
private int nextPort;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@@ -45,13 +63,24 @@ class RedshiftServerlessServiceTest {
|
||||
store = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
workgroupStore = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-workgroups.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) workgroupStore);
|
||||
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class)))
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
|
||||
+ invocation.getArgument(2, String.class));
|
||||
service = new RedshiftServerlessService(storageFactory, regionResolver);
|
||||
nextPort = 7100;
|
||||
endpoints = mock(RedshiftServerlessEndpoints.class);
|
||||
when(endpoints.allocate()).thenAnswer(invocation -> new Endpoint("localhost", nextPort++));
|
||||
runtime = mock(RedshiftServerlessRuntime.class);
|
||||
when(runtime.generatePassword()).thenReturn("Generated123");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
|
||||
service = new RedshiftServerlessService(storageFactory, regionResolver, endpoints, runtime);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -300,7 +329,483 @@ class RedshiftServerlessServiceTest {
|
||||
assertEquals(Map.of("env", "dev"), original.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupAppliesAwsDefaultsAndAllocatesAnEndpoint() {
|
||||
create("wg-ns");
|
||||
|
||||
Workgroup workgroup = createWorkgroup("wg-one", "wg-ns");
|
||||
|
||||
assertEquals("AVAILABLE", workgroup.getStatus());
|
||||
assertEquals("wg-ns", workgroup.getNamespaceName());
|
||||
assertEquals(128, workgroup.getBaseCapacity());
|
||||
assertEquals(5439, workgroup.getPort());
|
||||
assertEquals("ipv4", workgroup.getIpAddressType());
|
||||
assertEquals("current", workgroup.getTrackName());
|
||||
assertEquals("DISABLED", workgroup.getPricePerformanceTarget().getStatus());
|
||||
assertEquals("localhost", workgroup.getEndpoint().getAddress());
|
||||
assertEquals(7100, workgroup.getEndpoint().getPort());
|
||||
assertEquals("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":workgroup/" + workgroup.getWorkgroupId(),
|
||||
workgroup.getWorkgroupArn());
|
||||
assertEquals(workgroup.getWorkgroupId(), UUID.fromString(workgroup.getWorkgroupId()).toString());
|
||||
assertEquals("wg-one", service.getWorkgroup("wg-one", REGION).getWorkgroupName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupRequiresAnExistingNamespace() {
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> createWorkgroup("wg-orphan", "absent-ns")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceHasAtMostOneWorkgroupAndWorkgroupNamesAreUnique() {
|
||||
create("one-ns");
|
||||
create("two-ns");
|
||||
createWorkgroup("wg-first", "one-ns");
|
||||
|
||||
assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> createWorkgroup("wg-second", "one-ns")).getErrorCode());
|
||||
assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> createWorkgroup("wg-first", "two-ns")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupNamesAndSettingsAreValidated() {
|
||||
create("valid-ns");
|
||||
for (String name : List.of("ab", "Upper-Case", "has_underscore")) {
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> createWorkgroup(name, "valid-ns")).getErrorCode(), name);
|
||||
}
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createWorkgroup("bad-port", "valid-ns", settings(5000, null, null, null), null, REGION))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createWorkgroup("bad-ip", "valid-ns", settings(null, "ipv6", null, null), null, REGION))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createWorkgroup("bad-target", "valid-ns",
|
||||
settings(null, null, new PricePerformanceTarget("MAYBE", null), null), null, REGION))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createWorkgroup("bad-level", "valid-ns",
|
||||
settings(null, null, new PricePerformanceTarget("ENABLED", 101), null), null, REGION))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createWorkgroup("bad-track", "valid-ns", settings(null, null, null, "no-dashes"), null, REGION))
|
||||
.getErrorCode());
|
||||
assertTrue(service.listWorkgroups(REGION, null, null).items().isEmpty(),
|
||||
"a rejected create must leave nothing behind");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptedPortsIncludeBothDocumentedRanges() {
|
||||
create("ports-ns");
|
||||
create("ports-two-ns");
|
||||
assertEquals(5431, service.createWorkgroup("low-port", "ports-ns",
|
||||
settings(5431, null, null, null), null, REGION).getPort());
|
||||
assertEquals(8215, service.createWorkgroup("high-port", "ports-two-ns",
|
||||
settings(8215, null, null, null), null, REGION).getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAndDeleteRejectAnUnknownWorkgroup() {
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.getWorkgroup("absent-wg", REGION)).getErrorCode());
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.deleteWorkgroup("absent-wg", REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorkgroupAppliesOnlySuppliedFieldsAndRecordsAPendingTrack() {
|
||||
create("upd-ns");
|
||||
service.createWorkgroup("upd-wg", "upd-ns", new WorkgroupSettings(32, 64, null, true, null,
|
||||
List.of(new ConfigParameter("datestyle", "ISO, MDY")), List.of("sg-1"), List.of("subnet-1"),
|
||||
null, null, null, null), null, REGION);
|
||||
|
||||
Workgroup updated = service.updateWorkgroup("upd-wg", new WorkgroupSettings(null, 128, null, null, null,
|
||||
null, null, null, null, null, null, "trailing"), REGION);
|
||||
|
||||
assertEquals(32, updated.getBaseCapacity());
|
||||
assertEquals(128, updated.getMaxCapacity());
|
||||
assertTrue(updated.isPubliclyAccessible());
|
||||
assertEquals("datestyle", updated.getConfigParameters().get(0).getParameterKey());
|
||||
assertEquals(List.of("sg-1"), updated.getSecurityGroupIds());
|
||||
assertEquals("current", updated.getTrackName());
|
||||
assertEquals("trailing", updated.getPendingTrackName());
|
||||
|
||||
Workgroup reverted = service.updateWorkgroup("upd-wg", new WorkgroupSettings(null, null, null, null, null,
|
||||
null, null, null, null, null, null, "current"), REGION);
|
||||
assertNull(reverted.getPendingTrackName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStoresACopySoAReaderNeverSeesAHalfAppliedWorkgroupChange() {
|
||||
create("copy-wg-ns");
|
||||
createWorkgroup("copy-wg", "copy-wg-ns");
|
||||
Workgroup before = service.getWorkgroup("copy-wg", REGION);
|
||||
|
||||
service.updateWorkgroup("copy-wg", new WorkgroupSettings(64, null, null, null, null,
|
||||
null, null, null, null, null, null, null), REGION);
|
||||
|
||||
assertNotSame(before, service.getWorkgroup("copy-wg", REGION));
|
||||
assertEquals(128, before.getBaseCapacity());
|
||||
assertEquals(64, service.getWorkgroup("copy-wg", REGION).getBaseCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWorkgroupReportsDeletingReleasesTheEndpointAndFreesTheNamespace() {
|
||||
create("del-wg-ns");
|
||||
Workgroup created = createWorkgroup("del-wg", "del-wg-ns");
|
||||
|
||||
Workgroup deleted = service.deleteWorkgroup("del-wg", REGION);
|
||||
|
||||
assertEquals("DELETING", deleted.getStatus());
|
||||
verify(endpoints).release(created.getEndpoint());
|
||||
assertThrows(AwsException.class, () -> service.getWorkgroup("del-wg", REGION));
|
||||
createWorkgroup("del-wg-again", "del-wg-ns");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNamespaceIsRejectedWhileAWorkgroupIsAttached() {
|
||||
create("attached-ns");
|
||||
createWorkgroup("attached-wg", "attached-ns");
|
||||
|
||||
assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> service.deleteNamespace("attached-ns", REGION)).getErrorCode());
|
||||
assertEquals("attached-ns", service.getNamespace("attached-ns", REGION).getNamespaceName());
|
||||
|
||||
service.deleteWorkgroup("attached-wg", REGION);
|
||||
assertEquals("DELETING", service.deleteNamespace("attached-ns", REGION).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listWorkgroupsIsScopedToTheRegionAndPaginates() {
|
||||
create("list-a-ns");
|
||||
create("list-b-ns");
|
||||
service.createNamespace("list-w-ns", "admin", null, null, null, null, null, Map.of(), "us-west-2");
|
||||
createWorkgroup("alpha-wg", "list-a-ns");
|
||||
createWorkgroup("beta-wg", "list-b-ns");
|
||||
service.createWorkgroup("gamma-wg", "list-w-ns", emptySettings(), null, "us-west-2");
|
||||
|
||||
assertEquals(List.of("alpha-wg", "beta-wg"),
|
||||
service.listWorkgroups(REGION, null, null).items().stream().map(Workgroup::getWorkgroupName).toList());
|
||||
PaginatedResult<Workgroup> firstPage = service.listWorkgroups(REGION, 1, null);
|
||||
assertEquals(List.of("alpha-wg"), firstPage.items().stream().map(Workgroup::getWorkgroupName).toList());
|
||||
assertEquals(List.of("beta-wg"), service.listWorkgroups(REGION, 1, firstPage.nextToken()).items().stream()
|
||||
.map(Workgroup::getWorkgroupName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void workgroupTagsAreManagedThroughTheWorkgroupArn() {
|
||||
create("tag-wg-ns");
|
||||
Workgroup created = service.createWorkgroup("tag-wg", "tag-wg-ns", emptySettings(),
|
||||
Map.of("env", "dev"), REGION);
|
||||
String arn = created.getWorkgroupArn();
|
||||
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
|
||||
service.tagResource(arn, Map.of("team", "data"), REGION);
|
||||
assertEquals(Map.of("env", "dev", "team", "data"), service.listTagsForResource(arn, REGION));
|
||||
service.untagResource(arn, List.of("env"), REGION);
|
||||
assertEquals(Map.of("team", "data"), service.listTagsForResource(arn, REGION));
|
||||
|
||||
// The namespace's own tags are a separate set.
|
||||
assertTrue(service.listTagsForResource(service.getNamespace("tag-wg-ns", REGION).getNamespaceArn(), REGION)
|
||||
.isEmpty());
|
||||
verify(workgroupStore, atLeastOnce()).put(eq(REGION + "::tag-wg"), any(Workgroup.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearRemovesWorkgroupsAndReleasesTheirEndpoints() {
|
||||
create("clear-wg-ns");
|
||||
Workgroup created = createWorkgroup("clear-wg", "clear-wg-ns");
|
||||
|
||||
service.clear();
|
||||
|
||||
assertTrue(service.listWorkgroups(REGION, null, null).items().isEmpty());
|
||||
verify(endpoints).release(created.getEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWorkgroupStartsTheRuntimeWithTheNamespaceAdminAndRecordsWhereItListens() {
|
||||
service.createNamespace("rt-ns", "root", "Secret123", "analytics", null, null, null, null, Map.of(), REGION);
|
||||
|
||||
Workgroup workgroup = createWorkgroup("rt-wg", "rt-ns");
|
||||
|
||||
verify(runtime).start(eq(ACCOUNT_ID), eq(REGION), eq("rt-wg"), eq("root"), eq("Secret123"),
|
||||
eq("analytics"), eq(workgroup.getEndpoint()), eq(false), any());
|
||||
Workgroup stored = service.getWorkgroup("rt-wg", REGION);
|
||||
assertEquals("127.0.0.1", stored.getRuntimeHost());
|
||||
assertEquals(55432, stored.getRuntimePort());
|
||||
assertEquals("root", stored.getMasterUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceWithoutAPasswordGetsAGeneratedOneThatIsKeptForTheBackend() {
|
||||
service.createNamespace("gen-ns", null, null, null, null, null, null, Map.of(), REGION);
|
||||
|
||||
createWorkgroup("gen-wg", "gen-ns");
|
||||
|
||||
verify(runtime).start(eq(ACCOUNT_ID), eq(REGION), eq("gen-wg"), eq("admin"), eq("Generated123"),
|
||||
eq("dev"), any(Endpoint.class), eq(false), any());
|
||||
assertEquals("Generated123", store.get(REGION + "::gen-ns").orElseThrow().getAdminUserPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminSupplierHandedToTheRuntimeTracksTheNamespaceAsItChanges() {
|
||||
service.createNamespace("sup-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("sup-wg", "sup-ns");
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Supplier<Optional<RedshiftServerlessRuntime.AdminCredentials>>> supplier =
|
||||
ArgumentCaptor.forClass(Supplier.class);
|
||||
verify(runtime).start(any(), any(), any(), any(), any(), any(), any(), anyBoolean(), supplier.capture());
|
||||
|
||||
assertEquals(new RedshiftServerlessRuntime.AdminCredentials("root", "Secret123"),
|
||||
supplier.getValue().get().orElseThrow());
|
||||
service.updateNamespace("sup-ns", "renamed", "Changed123", null, null, null, null, REGION);
|
||||
|
||||
assertEquals(new RedshiftServerlessRuntime.AdminCredentials("renamed", "Changed123"),
|
||||
supplier.getValue().get().orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuntimeThatFailsToStartLeavesNoWorkgroupAndReleasesTheEndpoint() {
|
||||
create("fail-ns");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenThrow(new AwsException("InternalFailure", "Failed to start container", 500));
|
||||
|
||||
assertThrows(AwsException.class, () -> createWorkgroup("fail-wg", "fail-ns"));
|
||||
|
||||
assertTrue(service.listWorkgroups(REGION, null, null).items().isEmpty());
|
||||
verify(endpoints).release(any(Endpoint.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedPersistAfterTheRuntimeStartedStopsTheRuntimeAndReleasesTheEndpoint() {
|
||||
create("persist-ns");
|
||||
doThrow(new IllegalStateException("disk full")).when(workgroupStore)
|
||||
.put(eq(REGION + "::persist-wg"), any(Workgroup.class));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> createWorkgroup("persist-wg", "persist-ns"));
|
||||
|
||||
verify(runtime).stop(ACCOUNT_ID, REGION, "persist-wg");
|
||||
verify(endpoints).release(any(Endpoint.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWorkgroupStopsTheRuntimeFirstAndKeepsTheWorkgroupWhenThatFails() {
|
||||
create("stop-ns");
|
||||
createWorkgroup("stop-wg", "stop-ns");
|
||||
doThrow(new RuntimeException("listener would not close")).when(runtime).stop(ACCOUNT_ID, REGION, "stop-wg");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.deleteWorkgroup("stop-wg", REGION));
|
||||
|
||||
assertEquals("InternalServerException", failure.getErrorCode());
|
||||
assertEquals("stop-wg", service.getWorkgroup("stop-wg", REGION).getWorkgroupName());
|
||||
verify(endpoints, never()).release(any(Endpoint.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheAdminPasswordReachesTheRunningBackendBeforeItIsStored() {
|
||||
service.createNamespace("pw-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("pw-wg", "pw-ns");
|
||||
|
||||
service.updateNamespace("pw-ns", null, "Changed123", null, null, null, null, REGION);
|
||||
|
||||
verify(runtime).changeMasterPassword(ACCOUNT_ID, REGION, "pw-wg", "root", "dev", "Secret123", "Changed123");
|
||||
assertEquals("Changed123", store.get(REGION + "::pw-ns").orElseThrow().getAdminUserPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPasswordTheBackendRefusesLeavesTheNamespaceUnchangedAndIsAValidationError() {
|
||||
service.createNamespace("bad-pw-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("bad-pw-wg", "bad-pw-ns");
|
||||
doThrow(new AwsException("InvalidParameterValue", "too short", 400)).when(runtime)
|
||||
.changeMasterPassword(any(), any(), any(), any(), any(), any(), eq("short"));
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> service.updateNamespace("bad-pw-ns", null, "short", null, null, null, null, REGION));
|
||||
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
assertEquals("Secret123", store.get(REGION + "::bad-pw-ns").orElseThrow().getAdminUserPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceThatCannotBeStoredPutsTheBackendPasswordBack() {
|
||||
service.createNamespace("undo-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("undo-wg", "undo-ns");
|
||||
doThrow(new IllegalStateException("disk full")).when(store)
|
||||
.put(eq(REGION + "::undo-ns"), any(Namespace.class));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> service.updateNamespace("undo-ns", null, "Changed123", null, null, null, null, REGION));
|
||||
|
||||
verify(runtime).restoreMasterPassword(ACCOUNT_ID, REGION, "undo-wg", "root", "dev", "Secret123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedPasswordRestoreDoesNotMaskTheStorageFailure() {
|
||||
service.createNamespace("mask-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("mask-wg", "mask-ns");
|
||||
IllegalStateException storageFailure = new IllegalStateException("disk full");
|
||||
doThrow(storageFailure).when(store).put(eq(REGION + "::mask-ns"), any(Namespace.class));
|
||||
doThrow(new RuntimeException("psql failed")).when(runtime)
|
||||
.restoreMasterPassword(any(), any(), any(), any(), any(), any());
|
||||
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class,
|
||||
() -> service.updateNamespace("mask-ns", null, "Changed123", null, null, null, null, REGION));
|
||||
|
||||
assertEquals(storageFailure, thrown);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceUpdateThatFailsValidationNeverTouchesTheBackendPassword() {
|
||||
service.createNamespace("order-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("order-wg", "order-ns");
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateNamespace(
|
||||
"order-ns", null, "Changed123", null, null, null, List.of("bogus"), REGION));
|
||||
|
||||
verify(runtime, never()).changeMasterPassword(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconcileNamespaceResetsAnOmittedKmsKeyAndDefaultRole() {
|
||||
service.createNamespace("rec-ns", "root", null, null, "custom-key", "arn:aws:iam::000000000000:role/r",
|
||||
null, null, Map.of(), REGION);
|
||||
|
||||
Namespace reconciled = service.reconcileNamespace("rec-ns", null, null, null, null, null, null, REGION);
|
||||
|
||||
assertEquals(RedshiftServerlessService.AWS_OWNED_KMS_KEY, reconciled.getKmsKeyId());
|
||||
assertNull(reconciled.getDefaultIamRoleArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNamespaceKeepsAnOmittedKmsKeyAndDefaultRole() {
|
||||
service.createNamespace("keep-ns", "root", null, null, "custom-key", "arn:aws:iam::000000000000:role/r",
|
||||
null, null, Map.of(), REGION);
|
||||
|
||||
Namespace updated = service.updateNamespace("keep-ns", null, null, null, null, null, null, REGION);
|
||||
|
||||
assertEquals("custom-key", updated.getKmsKeyId());
|
||||
assertEquals("arn:aws:iam::000000000000:role/r", updated.getDefaultIamRoleArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearKeepsTheEndpointReservedWhenTheRuntimeCannotBeStopped() {
|
||||
create("hold-ns");
|
||||
Workgroup created = createWorkgroup("hold-wg", "hold-ns");
|
||||
doThrow(new RuntimeException("listener still bound")).when(runtime).stop(ACCOUNT_ID, REGION, "hold-wg");
|
||||
|
||||
service.clear();
|
||||
|
||||
verify(endpoints, never()).release(created.getEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAdminPasswordChangeWithNoWorkgroupJustStoresIt() {
|
||||
service.createNamespace("solo-ns", "root", null, null, null, null, null, null, Map.of(), REGION);
|
||||
|
||||
service.updateNamespace("solo-ns", null, "Changed123", null, null, null, null, REGION);
|
||||
|
||||
verify(runtime, never()).changeMasterPassword(any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals("Changed123", store.get(REGION + "::solo-ns").orElseThrow().getAdminUserPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCredentialsMintsForTheDbUserWithTheDocumentedDurations() {
|
||||
create("cred-ns");
|
||||
createWorkgroup("cred-wg", "cred-ns");
|
||||
TempCredential minted = new TempCredential("IAM:alice", "pw", Instant.parse("2026-10-03T00:15:00Z"), List.of());
|
||||
when(runtime.issueCredential(ACCOUNT_ID, REGION, "cred-wg", "IAM:alice", 900)).thenReturn(minted);
|
||||
when(runtime.issueCredential(ACCOUNT_ID, REGION, "cred-wg", "IAM:alice", 3600)).thenReturn(minted);
|
||||
|
||||
assertEquals(minted, service.getCredentials("cred-wg", null, null, "IAM:alice", REGION));
|
||||
assertEquals(minted, service.getCredentials("cred-wg", "dev", 3600, "IAM:alice", REGION));
|
||||
for (int bad : new int[] {899, 3601}) {
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.getCredentials("cred-wg", null, bad, "IAM:alice", REGION)).getErrorCode());
|
||||
}
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.getCredentials("cred-wg", "other", null, "IAM:alice", REGION)).getErrorCode());
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.getCredentials("absent-wg", null, null, "IAM:alice", REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupTargetResolvesByNameOrArnAndNeedsALiveRuntime() {
|
||||
service.createNamespace("tgt-ns", "root", "Secret123", "analytics", null, null, null, null, Map.of(), REGION);
|
||||
Workgroup created = createWorkgroup("tgt-wg", "tgt-ns");
|
||||
|
||||
for (String reference : List.of("tgt-wg", created.getWorkgroupArn())) {
|
||||
RedshiftServerlessService.WorkgroupTarget target = service.getWorkgroupTarget(reference, REGION);
|
||||
assertEquals(created.getWorkgroupArn(), target.arn());
|
||||
assertEquals("127.0.0.1", target.host());
|
||||
assertEquals(55432, target.port());
|
||||
assertEquals("analytics", target.database());
|
||||
assertEquals("root", target.masterUsername());
|
||||
assertEquals("Secret123", target.masterPassword());
|
||||
}
|
||||
String absentArn = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID
|
||||
+ ":workgroup/00000000-0000-0000-0000-000000000000";
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.getWorkgroupTarget(absentArn, REGION)).getErrorCode());
|
||||
|
||||
Workgroup dead = new Workgroup(service.getWorkgroup("tgt-wg", REGION));
|
||||
dead.setRuntimeHost(null);
|
||||
dead.setRuntimePort(0);
|
||||
workgroupStore.put(REGION + "::tgt-wg", dead);
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.getWorkgroupTarget("tgt-wg", REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupRestoresEachWorkgroupRuntimeAndClearsTheOnesItCannotRestore() {
|
||||
service.createNamespace("rec-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
service.createNamespace("rec-bad-ns", "root", "Secret123", null, null, null, null, null, Map.of(), REGION);
|
||||
createWorkgroup("rec-wg", "rec-ns");
|
||||
createWorkgroup("rec-bad-wg", "rec-bad-ns");
|
||||
when(endpoints.restore(any(Endpoint.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(runtime.start(any(String.class), any(String.class), eq("rec-bad-wg"), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), eq(true), any()))
|
||||
.thenThrow(new AwsException("InternalFailure", "no container", 500));
|
||||
when(runtime.start(any(String.class), any(String.class), eq("rec-wg"), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), eq(true), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("10.0.0.9", 6000));
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
assertEquals("10.0.0.9", service.getWorkgroup("rec-wg", REGION).getRuntimeHost());
|
||||
assertEquals(6000, service.getWorkgroup("rec-wg", REGION).getRuntimePort());
|
||||
assertNull(service.getWorkgroup("rec-bad-wg", REGION).getRuntimeHost());
|
||||
assertEquals(0, service.getWorkgroup("rec-bad-wg", REGION).getRuntimePort());
|
||||
assertEquals("AVAILABLE", service.getWorkgroup("rec-bad-wg", REGION).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearStopsEveryRuntime() {
|
||||
create("clr-ns");
|
||||
createWorkgroup("clr-wg", "clr-ns");
|
||||
|
||||
service.clear();
|
||||
|
||||
verify(runtime).stop(ACCOUNT_ID, REGION, "clr-wg");
|
||||
}
|
||||
|
||||
private Namespace create(String namespaceName) {
|
||||
return service.createNamespace(namespaceName, "admin", null, null, null, null, null, Map.of(), REGION);
|
||||
}
|
||||
|
||||
private Workgroup createWorkgroup(String workgroupName, String namespaceName) {
|
||||
return service.createWorkgroup(workgroupName, namespaceName, emptySettings(), null, REGION);
|
||||
}
|
||||
|
||||
private static WorkgroupSettings emptySettings() {
|
||||
return new WorkgroupSettings(null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static WorkgroupSettings settings(Integer port, String ipAddressType, PricePerformanceTarget target,
|
||||
String trackName) {
|
||||
return new WorkgroupSettings(null, null, null, null, null, null, null, null, port, target,
|
||||
ipAddressType, trackName);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user