Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(redshift-serverless): accept customDomainName in GetCredentials (#5856)

Vũ Thế Huy1cb8b0f7471a
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java
index d4824cf1ff..dfad634789 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java
@@ -365,8 +365,25 @@ class RedshiftServerlessTest {
.customDomainName("db.example.com").customDomainCertificateArn(certificate));
assertThat(client.listCustomDomainAssociations(request -> request.customDomainName("db.example.com"))
.associations()).hasSize(1);
+
+ GetCredentialsResponse credentials = client.getCredentials(request -> request
+ .customDomainName("db.example.com")
+ .dbName("dev"));
+ assertThat(credentials.dbUser()).isNotBlank();
+ assertThat(credentials.dbPassword()).isNotBlank();
+ assertThat(credentials.expiration()).isAfter(Instant.now());
+
+ assertThatThrownBy(() -> client.getCredentials(request -> request
+ .customDomainName("db.example.com")
+ .workgroupName(workgroupName)))
+ .isInstanceOf(ValidationException.class);
+
client.deleteCustomDomainAssociation(request -> request.workgroupName(workgroupName)
.customDomainName("db.example.com"));
+
+ assertThatThrownBy(() -> client.getCredentials(request -> request
+ .customDomainName("db.example.com")))
+ .isInstanceOf(ResourceNotFoundException.class);
} finally {
deleteWorkgroupBestEffort(client, workgroupName);
deleteBestEffort(client, namespaceName);
diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.md
index 92fe42f315..59716ba24a 100644
--- a/docs/services/redshift-serverless.md
+++ b/docs/services/redshift-serverless.md
@@ -70,7 +70,7 @@ Namespace and workgroup state is account and Region scoped and persisted through
- **A workgroup runs a real PostgreSQL container.** `CreateWorkgroup` starts the container (this needs Docker and uses `floci.services.redshift.image-version`) and an authenticating proxy on the `endpoint`, whose port comes from the same pool as provisioned Redshift clusters (`floci.services.redshift.proxy-base-port` to `proxy-max-port`). Connect with any PostgreSQL client or JDBC driver using the namespace admin user and password, to the namespace `dbName`. The Redshift Data API accepts `WorkgroupName` ([details](redshift-data.md)). Only the operations in the Supported Actions table are served. The rest of the Redshift Serverless API is not emulated and answers `UnknownOperationException`: snapshot copy configurations, snapshot restore access policies, recovery points, table restore and restore status, endpoint access, resource policies, custom domain associations, scheduled actions, reservations and reservation offerings, tracks, managed workgroups, the Identity Center token, and lakehouse configuration.
- **Admin credentials come from the namespace.** The backend role is the namespace `adminUsername` (default `admin`) and the password is the `adminUserPassword` the namespace was created with. A namespace created without a password gets a generated one that is kept internally and never returned, so such a workgroup is reachable through `GetCredentials` and the Data API only. `manageAdminPassword` still creates no secret. Changing `adminUserPassword` with `UpdateNamespace` takes effect for new connections and is refused with `ValidationException` if the backend rejects it (AWS password rules: 8 to 64 characters with upper case, lower case and a digit, and none of `' " / @`). Changing `adminUsername` on a running workgroup does not rename the backend role; the new name is accepted at the proxy, which opens the backend as the original role.
-- **`GetCredentials` returns a master-equivalent password.** `dbUser` is derived from the signing identity (`IAM:<user>` or `IAMR:<role>`, falling back to `IAMR:floci` when the caller cannot be resolved), `dbPassword` is random, and `expiration` and `nextRefreshTime` are epoch seconds (the same instant). `durationSeconds` defaults to 900 and must be 900 to 3600. `dbName`, when given, must be the namespace `dbName`. `customDomainName` is not supported. A returned credential stays valid until it expires or the workgroup is deleted.
+- **`GetCredentials` returns a master-equivalent password.** `dbUser` is derived from the signing identity (`IAM:<user>` or `IAMR:<role>`, falling back to `IAMR:floci` when the caller cannot be resolved), `dbPassword` is random, and `expiration` and `nextRefreshTime` are epoch seconds (the same instant). `durationSeconds` defaults to 900 and must be 900 to 3600. `dbName`, when given, must be the namespace `dbName`. `customDomainName` can be used in place of `workgroupName` to resolve the associated workgroup. A returned credential stays valid until it expires or the workgroup is deleted.
- **The runtime survives a restart when its container does.** On startup Floci re-attaches to the container and restarts the proxy on the same port, so the endpoint is stable. If the container is gone the workgroup comes back with an empty database; if neither can be started, the workgroup stays `AVAILABLE`, the Data API reports that its runtime is not available, and the failure is logged. Containers have no Docker volume, as for provisioned clusters.
- **`adminUserPassword` is accepted and never returned**, matching AWS. No secret is created for `manageAdminPassword`.
- **Defaults follow AWS.** `dbName` defaults to `dev`, `kmsKeyId` to `AWS_OWNED_KMS_KEY`, `logExports` to an empty list, and `status` to `AVAILABLE` immediately: there is no `MODIFYING` or `CREATING` phase to poll through.
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessCustomDomainService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessCustomDomainService.java
index 54c5443b47..7d4dc75e4b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessCustomDomainService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessCustomDomainService.java
@@ -87,6 +87,11 @@ public class RedshiftServerlessCustomDomainService implements Resettable {
.map(association -> withCertificateExpiry(association, region));
}
+ public synchronized Optional<CustomDomainAssociation> findForCustomDomain(String customDomainName, String region) {
+ return Optional.ofNullable(findByDomain(customDomainName, region))
+ .map(association -> withCertificateExpiry(association, region));
+ }
+
public synchronized PaginatedResult<CustomDomainAssociation> listCustomDomainAssociations(
String customDomainName, String certificateArn, String region, Integer maxResults, String nextToken) {
int limit = ServerlessSupport.pageSize(maxResults);
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java
index 46233f1d4b..d77c796fd0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.redshift.RedshiftIamDbUserResolver;
import io.github.hectorvent.floci.services.redshift.TempCredential;
import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter;
+import io.github.hectorvent.floci.services.redshiftserverless.model.CustomDomainAssociation;
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.RedshiftServerlessSnapshot;
@@ -200,11 +201,8 @@ public class RedshiftServerlessJsonHandler {
* refreshes an authorization early, so the refresh time is the expiry.
*/
private Response handleGetCredentials(JsonNode request, String region, String authorizationHeader) {
- if (request.hasNonNull("customDomainName")) {
- throw ServerlessSupport.validation("customDomainName is not supported; use workgroupName.");
- }
TempCredential credential = service.getCredentials(
- ServerlessSupport.text(request, "workgroupName"),
+ workgroupNameOf(request, region),
ServerlessSupport.text(request, "dbName"),
ServerlessSupport.integer(request, "durationSeconds"),
iamDbUserResolver.resolveDbUser(authorizationHeader),
@@ -217,6 +215,28 @@ public class RedshiftServerlessJsonHandler {
return Response.ok(response).build();
}
+ /**
+ * Resolves the workgroup name from {@code workgroupName}, or from {@code customDomainName} when given.
+ * AWS requires exactly one of the two to identify the target workgroup.
+ */
+ private String workgroupNameOf(JsonNode request, String region) {
+ String workgroupName = ServerlessSupport.text(request, "workgroupName");
+ String customDomainName = ServerlessSupport.text(request, "customDomainName");
+ if (workgroupName != null && customDomainName != null) {
+ throw ServerlessSupport.validation("workgroupName and customDomainName cannot both be specified.");
+ }
+ if (workgroupName == null && customDomainName == null) {
+ throw ServerlessSupport.validation(
+ "The custom domain name or the workgroup name must be included in the request.");
+ }
+ if (customDomainName != null) {
+ return customDomains.findForCustomDomain(customDomainName, region)
+ .map(CustomDomainAssociation::getWorkgroupName)
+ .orElseThrow(() -> ServerlessSupport.notFound("The custom domain " + customDomainName + " was not found."));
+ }
+ return workgroupName;
+ }
+
private Response handleCreateSnapshot(JsonNode request, String region) {
return snapshotResponse(service.createSnapshot(
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.text(request, "namespaceName"),
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java
index 184b1e0e95..30d9529c4e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java
@@ -72,6 +72,9 @@ class RedshiftServerlessIntegrationTest {
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), "temporary-password",
+ Instant.now().plusSeconds(900), List.of()));
}
@ParameterizedTest
@@ -700,11 +703,24 @@ class RedshiftServerlessIntegrationTest {
call("ListCustomDomainAssociations", "{\"customDomainName\":\"db.example.com\"}")
.statusCode(200)
.body("associations", hasSize(1));
+ call("GetCredentials", "{\"customDomainName\":\"db.example.com\"}")
+ .statusCode(200)
+ .body("dbUser", notNullValue())
+ .body("dbPassword", notNullValue());
+ call("GetCredentials", "{\"customDomainName\":\"db.example.com\",\"workgroupName\":\"domain-wg\"}")
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ call("GetCredentials", "{\"customDomainName\":\"missing.example.com\"}")
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"));
call("DeleteCustomDomainAssociation",
"{\"workgroupName\":\"domain-wg\",\"customDomainName\":\"db.example.com\"}").statusCode(200);
call("GetWorkgroup", "{\"workgroupName\":\"domain-wg\"}")
.statusCode(200)
.body("workgroup.customDomainName", nullValue());
+ call("GetCredentials", "{\"customDomainName\":\"db.example.com\"}")
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java
index 456f22b45f..6cf515ff60 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java
@@ -244,7 +244,26 @@ class RedshiftServerlessJsonHandlerTest {
}
@Test
- void getCredentialsRejectsABadDurationAMissingWorkgroupAndACustomDomain() {
+ void getCredentialsAcceptsACustomDomainNameInPlaceOfWorkgroupName() {
+ create("cred-dom-ns");
+ body(handler.handle("CreateWorkgroup",
+ parse("{\"workgroupName\":\"cred-dom-wg\",\"namespaceName\":\"cred-dom-ns\"}"), REGION));
+ body(handler.handle("CreateCustomDomainAssociation",
+ parse("{\"workgroupName\":\"cred-dom-wg\",\"customDomainName\":\"db.example.com\","
+ + "\"customDomainCertificateArn\":\"arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555\"}"),
+ REGION));
+
+ JsonNode credentials = body(handler.handle("GetCredentials",
+ parse("{\"customDomainName\":\"db.example.com\",\"dbName\":\"dev\",\"durationSeconds\":1800}"),
+ REGION, "AUTH"));
+
+ assertEquals("IAM:alice", credentials.get("dbUser").textValue());
+ assertEquals("tempPassword1", credentials.get("dbPassword").textValue());
+ assertEquals(1_800_000_000L, credentials.get("expiration").longValue());
+ }
+
+ @Test
+ void getCredentialsRejectsInvalidParametersAndUnknownTargets() {
create("cred-err-ns");
body(handler.handle("CreateWorkgroup",
parse("{\"workgroupName\":\"cred-err-wg\",\"namespaceName\":\"cred-err-ns\"}"), REGION));
@@ -258,14 +277,29 @@ class RedshiftServerlessJsonHandlerTest {
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(400, 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));
+ Response missingWorkgroup = handler.handle("GetCredentials",
+ parse("{\"workgroupName\":\"absent-wg\"}"), REGION, "AUTH");
+ assertEquals(400, missingWorkgroup.getStatus());
+ assertEquals("ResourceNotFoundException", errorType(missingWorkgroup));
+
+ Response missingDomain = handler.handle("GetCredentials",
+ parse("{\"customDomainName\":\"absent.example.com\"}"), REGION, "AUTH");
+ assertEquals(400, missingDomain.getStatus());
+ assertEquals("ResourceNotFoundException", errorType(missingDomain));
+
+ Response both = handler.handle("GetCredentials",
+ parse("{\"workgroupName\":\"cred-err-wg\",\"customDomainName\":\"wg.example.com\"}"), REGION, "AUTH");
+ assertEquals(400, both.getStatus());
+ assertEquals("ValidationException", errorType(both));
+
+ Response neither = handler.handle("GetCredentials", parse("{}"), REGION, "AUTH");
+ assertEquals(400, neither.getStatus());
+ assertEquals("ValidationException", errorType(neither));
+
+ Response badDomain = handler.handle("GetCredentials",
+ parse("{\"customDomainName\":\"-bad\"}"), REGION, "AUTH");
+ assertEquals(400, badDomain.getStatus());
+ assertEquals("ValidationException", errorType(badDomain));
}
@Test