mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshiftserverless): add namespace lifecycle and tagging (#3631)
* feat(redshiftserverless): add namespace lifecycle Amazon Redshift Serverless was absent entirely: every call returned UnknownOperationException, so Terraform's aws_redshiftserverless_namespace could not be planned or applied against Floci. Add a JSON 1.1 service under the RedshiftServerless. target prefix with CreateNamespace, GetNamespace, ListNamespaces, UpdateNamespace, and DeleteNamespace. Namespaces are account and Region scoped and stored through StorageFactory. AWS defaults are applied on create (dbName dev, kmsKeyId AWS_OWNED_KMS_KEY, empty logExports, status AVAILABLE), adminUserPassword is accepted and never returned, DeleteNamespace returns the removed namespace with status DELETING, and UpdateNamespace applies only the supplied fields. Workgroups, snapshots, and the tagging operations remain unemulated. * feat(redshiftserverless): add namespace tagging operations Terraform's aws_redshiftserverless_namespace calls ListTagsForResource on every read once tags are involved, so the namespace lifecycle alone left the resource broken as soon as a config set tags. Add ListTagsForResource, TagResource, and UntagResource. Lookup is by resourceArn rather than namespace name, scoped to the caller's Region, since that is how AWS keys these operations; the namespace is currently the only taggable Redshift Serverless resource, so any other ARN is reported absent. TagResource merges into the existing tags, UntagResource removes by key, and tags passed to CreateNamespace are readable back and survive UpdateNamespace. * fix(redshiftserverless): emit creationDate as ISO-8601 per the API model The awsJson1.1 default is epoch seconds and 133 call sites use it, but this model overrides it: TimestampFormatTrait ISO_8601 on creationDate (and on all eleven other timestamp members in the package, audited). Strict clients broke on the number: Terraform's Go SDK failed to decode and orphaned the created namespace outside state; the Java SDK failed to unmarshall. Only botocore's lenient parsing let CLI checks pass. Emitted via the repo's millisecond-ISO idiom; format pinned by regex in the integration test and by a new handler-level unit test class covering the wire layer that had none (timestamp shape, nextToken emission, maxResults type guard). Checklist note added to AGENTS.md + CONTRIBUTING.md so the next service checks the trait before reaching for the epoch idiom. * docs(redshiftserverless): the ISO-8601 rule is per member, not model-wide Review follow-up: the earlier claim that every timestamp member in this model carries TimestampFormatTrait(ISO_8601) is wrong — 15 of the model's 30 INSTANT members carry no trait and fall back to the awsJson1.1 epoch default. The shipped code is unaffected (creationDate, the only timestamp emitted, is genuinely ISO_8601), but the claim was load-bearing guidance: whoever adds snapshots or scheduled actions next would have applied ISO-8601 to trait-free members and reintroduced the bug in the opposite direction. Narrowed in all four places it appeared. * fix(redshiftserverless): validate collection types, copy-on-update; drop em dashes A present iamRoles, logExports, tags or tagKeys member that was not a JSON array parsed to null and was then indistinguishable from an omitted member, so a malformed UpdateNamespace silently kept the stored value and returned 200 instead of reporting the request as invalid. Only a missing or null member now means "omitted"; a present member of the wrong type, or a collection holding a non-string element, is a ValidationException naming the member. updateNamespace mutated the stored Namespace in place while GetNamespace and ListNamespaces read without taking the same monitor, so a concurrent reader could observe a torn object with some fields updated and some not. Build the new state on a copy and store that instead, which also makes the write-back explicit. The same in-place mutation was present in tagResource, untagResource and deleteNamespace, so all four now copy. Merge semantics are unchanged. Replace the em dashes in the timestamp guidance with commas and periods, per the repository ban. * fix(redshiftserverless): reject Redshift reserved words as namespace names CreateNamespace rejects a namespace name that is an Amazon Redshift SQL reserved word, so names like select or user passed the length and [a-z0-9-] checks here and were persisted. Add the documented reserved word list to the shared namespace-name validator, which create, get, update and delete all reach, so the rejection is consistent.
This commit is contained in:
1 parent
dc70f60a66
commit
4b3923712a
21 files changed
+1552
-10
No files matched your search
+176
@@ -0,0 +1,176 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftServerlessIntegrationTest {
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "RedshiftServerless.";
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/redshift-serverless/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAppliesAwsDefaultsAndNeverReturnsTheAdminPassword() {
|
||||
call("CreateNamespace", """
|
||||
{"namespaceName":"defaults-ns","adminUsername":"admin","adminUserPassword":"Secret123!"}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("namespace.namespaceName", equalTo("defaults-ns"))
|
||||
.body("namespace.namespaceId", matchesPattern(
|
||||
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))
|
||||
.body("namespace.namespaceArn", matchesPattern(
|
||||
"arn:aws:redshift-serverless:us-east-1:\\d{12}:namespace/"
|
||||
+ "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))
|
||||
.body("namespace.dbName", equalTo("dev"))
|
||||
.body("namespace.kmsKeyId", equalTo("AWS_OWNED_KMS_KEY"))
|
||||
.body("namespace.status", equalTo("AVAILABLE"))
|
||||
.body("namespace.adminUsername", equalTo("admin"))
|
||||
.body("namespace.logExports.size()", equalTo(0))
|
||||
.body("namespace.creationDate", matchesPattern(
|
||||
"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"))
|
||||
.body("namespace.adminUserPassword", nullValue());
|
||||
|
||||
call("GetNamespace", "{\"namespaceName\":\"defaults-ns\"}")
|
||||
.statusCode(200)
|
||||
.body("namespace.dbName", equalTo("dev"))
|
||||
.body("namespace.kmsKeyId", equalTo("AWS_OWNED_KMS_KEY"))
|
||||
.body("namespace.adminUserPassword", nullValue());
|
||||
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"defaults-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void namespaceLifecycleIsVisibleThroughSeparateReads() {
|
||||
call("CreateNamespace", """
|
||||
{"namespaceName":"lifecycle-ns","adminUsername":"admin","dbName":"analytics",
|
||||
"logExports":["userlog"],"iamRoles":["arn:aws:iam::000000000000:role/one"]}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("namespace.dbName", equalTo("analytics"));
|
||||
|
||||
call("ListNamespaces", "{}")
|
||||
.statusCode(200)
|
||||
.body("namespaces.namespaceName", hasItem("lifecycle-ns"));
|
||||
|
||||
call("UpdateNamespace", """
|
||||
{"namespaceName":"lifecycle-ns","kmsKeyId":"custom-key",
|
||||
"logExports":["userlog","connectionlog"],"iamRoles":[]}
|
||||
""")
|
||||
.statusCode(200);
|
||||
|
||||
call("GetNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")
|
||||
.statusCode(200)
|
||||
.body("namespace.kmsKeyId", equalTo("custom-key"))
|
||||
.body("namespace.logExports", hasItem("connectionlog"))
|
||||
.body("namespace.iamRoles.size()", equalTo(0))
|
||||
.body("namespace.dbName", equalTo("analytics"));
|
||||
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")
|
||||
.statusCode(200)
|
||||
.body("namespace.namespaceName", equalTo("lifecycle-ns"))
|
||||
.body("namespace.status", equalTo("DELETING"));
|
||||
|
||||
call("GetNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNamespaceNameIsRejected() {
|
||||
call("CreateNamespace", "{\"namespaceName\":\"conflict-ns\",\"adminUsername\":\"admin\"}")
|
||||
.statusCode(200);
|
||||
call("CreateNamespace", "{\"namespaceName\":\"conflict-ns\",\"adminUsername\":\"admin\"}")
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"));
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"conflict-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnUnknownNamespaceReturnsResourceNotFound() {
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"absent-ns\"}")
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidNamespaceNameReturnsValidationError() {
|
||||
call("CreateNamespace", "{\"namespaceName\":\"Upper-Case\",\"adminUsername\":\"admin\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLogExportReturnsValidationError() {
|
||||
call("CreateNamespace", """
|
||||
{"namespaceName":"bad-logs-ns","adminUsername":"admin","logExports":["nosuchlog"]}
|
||||
""")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsCreatedWithTheNamespaceAreReadableAndEditable() {
|
||||
String arn = call("CreateNamespace", """
|
||||
{"namespaceName":"tagged-ns","adminUsername":"admin","tags":[{"key":"env","value":"dev"}]}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("namespace.namespaceArn");
|
||||
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("tags.size()", equalTo(1))
|
||||
.body("tags[0].key", equalTo("env"))
|
||||
.body("tags[0].value", equalTo("dev"));
|
||||
|
||||
call("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"team\",\"value\":\"data\"}]}")
|
||||
.statusCode(200);
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("tags.key", hasItem("team"))
|
||||
.body("tags.key", hasItem("env"));
|
||||
|
||||
call("UntagResource", "{\"resourceArn\":\"" + arn + "\",\"tagKeys\":[\"env\"]}")
|
||||
.statusCode(200);
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("tags.size()", equalTo(1))
|
||||
.body("tags[0].key", equalTo("team"));
|
||||
|
||||
call("DeleteNamespace", "{\"namespaceName\":\"tagged-ns\"}").statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void taggingAnUnknownArnReturnsResourceNotFound() {
|
||||
String absent = "arn:aws:redshift-serverless:us-east-1:000000000000:"
|
||||
+ "namespace/00000000-0000-0000-0000-000000000000";
|
||||
call("ListTagsForResource", "{\"resourceArn\":\"" + absent + "\"}")
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.header("Authorization", AUTH)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
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 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.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Covers the wire layer the service tests cannot reach: how values are shaped on the way out.
|
||||
* The timestamp case is a regression guard. {@code creationDate} was first emitted as
|
||||
* epoch seconds, the awsJson1.1 default, but {@code Namespace.creationDate} carries
|
||||
* {@code TimestampFormatTrait(ISO_8601)} (other members of this model vary; check each). The AWS CLI accepted the number because
|
||||
* botocore coerces it, so an integration test asserting only "not null" stayed green while
|
||||
* strict SDKs rejected the response.
|
||||
*/
|
||||
class RedshiftServerlessJsonHandlerTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private RedshiftServerlessJsonHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
AccountAwareStorageBackend<Namespace> store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
|
||||
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));
|
||||
handler = new RedshiftServerlessJsonHandler(
|
||||
new RedshiftServerlessService(storageFactory, regionResolver), mapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationDateIsAnIso8601StringNotEpochSeconds() {
|
||||
JsonNode namespace = body(create("timestamp-ns")).get("namespace");
|
||||
|
||||
JsonNode creationDate = namespace.get("creationDate");
|
||||
assertTrue(creationDate.isTextual(),
|
||||
"creationDate must be a JSON string; a number is what strict SDKs reject");
|
||||
assertTrue(creationDate.textValue().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"),
|
||||
"unexpected creationDate shape: " + creationDate.textValue());
|
||||
// Parsed by the same ISO-8601 reader an SDK uses, so a well-formed string carrying a
|
||||
// wrong offset or a stale clock cannot pass on shape alone.
|
||||
Instant parsed = Instant.parse(creationDate.textValue());
|
||||
assertTrue(Duration.between(parsed, Instant.now()).abs().toMinutes() < 5,
|
||||
"creationDate is not close to now, check the zone offset: " + creationDate.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationDateSurvivesAReadBackThroughGetNamespace() {
|
||||
create("reread-ns");
|
||||
JsonNode fetched = body(handler.handle("GetNamespace", request("namespaceName", "reread-ns"), REGION));
|
||||
assertTrue(fetched.get("namespace").get("creationDate").isTextual());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listNamespacesEmitsNextTokenOnlyWhenAPageRemains() {
|
||||
create("page-one-ns");
|
||||
create("page-two-ns");
|
||||
|
||||
ObjectNode paged = request("maxResults", null);
|
||||
paged.put("maxResults", 1);
|
||||
JsonNode firstPage = body(handler.handle("ListNamespaces", paged, REGION));
|
||||
assertEquals(1, firstPage.get("namespaces").size());
|
||||
assertTrue(firstPage.hasNonNull("nextToken"), "a remaining page must advertise nextToken");
|
||||
|
||||
ObjectNode second = mapper.createObjectNode();
|
||||
second.put("maxResults", 1);
|
||||
second.put("nextToken", firstPage.get("nextToken").textValue());
|
||||
JsonNode lastPage = body(handler.handle("ListNamespaces", second, REGION));
|
||||
assertEquals(1, lastPage.get("namespaces").size());
|
||||
assertFalse(lastPage.has("nextToken"), "the final page must not advertise nextToken");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStringMaxResultsIsAValidationExceptionEvenWhenItLooksLikeANumber() {
|
||||
// "12" is the case that actually pins the type guard. A non-numeric string such as
|
||||
// "twelve" coerces to 0 through asInt() and is rejected downstream by the pagination
|
||||
// bound anyway, so it cannot tell a present guard from an absent one.
|
||||
for (String malformed : new String[] {"twelve", "12"}) {
|
||||
ObjectNode bad = mapper.createObjectNode();
|
||||
bad.put("maxResults", malformed);
|
||||
|
||||
Response response = handler.handle("ListNamespaces", bad, REGION);
|
||||
|
||||
assertEquals(400, response.getStatus(), "maxResults=\"" + malformed + "\" must be rejected");
|
||||
assertEquals("ValidationException", errorType(response),
|
||||
"maxResults=\"" + malformed + "\" must be a ValidationException");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownActionIsReportedAsUnknownOperation() {
|
||||
Response response = handler.handle("CreateWorkgroup", mapper.createObjectNode(), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("UnknownOperationException", errorType(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPresentCollectionMemberOfTheWrongTypeIsRejectedPerMember() {
|
||||
create("wrong-type-ns");
|
||||
|
||||
for (String member : new String[] {"iamRoles", "logExports"}) {
|
||||
for (String malformed : new String[] {"\"a-string\"", "7", "{\"k\":\"v\"}", "true"}) {
|
||||
ObjectNode request = (ObjectNode) parse(
|
||||
"{\"namespaceName\":\"wrong-type-ns\"," + quoted(member) + ":" + malformed + "}");
|
||||
|
||||
Response response = handler.handle("UpdateNamespace", request, REGION);
|
||||
|
||||
assertEquals(400, response.getStatus(),
|
||||
member + "=" + malformed + " must not be accepted");
|
||||
assertEquals("ValidationException", errorType(response),
|
||||
member + "=" + malformed + " must be a ValidationException");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongTypedCollectionIsNotSilentlyTreatedAsOmitted() {
|
||||
ObjectNode created = (ObjectNode) parse("{\"namespaceName\":\"not-omitted-ns\","
|
||||
+ "\"adminUsername\":\"admin\",\"iamRoles\":[\"arn:aws:iam::000000000000:role/one\"]}");
|
||||
body(handler.handle("CreateNamespace", created, REGION));
|
||||
|
||||
Response response = handler.handle("UpdateNamespace",
|
||||
(ObjectNode) parse("{\"namespaceName\":\"not-omitted-ns\",\"iamRoles\":\"role/one\"}"), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus(),
|
||||
"a malformed iamRoles must fail the request, not quietly keep the stored roles");
|
||||
JsonNode unchanged = body(handler.handle("GetNamespace",
|
||||
request("namespaceName", "not-omitted-ns"), REGION)).get("namespace");
|
||||
assertEquals(1, unchanged.get("iamRoles").size(), "the rejected update must not have applied");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonStringElementsInACollectionAreRejected() {
|
||||
create("bad-element-ns");
|
||||
|
||||
Response response = handler.handle("UpdateNamespace",
|
||||
(ObjectNode) parse("{\"namespaceName\":\"bad-element-ns\",\"iamRoles\":[7]}"), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("ValidationException", errorType(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongTypedTagsOrTagKeysMemberIsRejected() {
|
||||
JsonNode namespace = body(create("tag-type-ns")).get("namespace");
|
||||
String arn = namespace.get("namespaceArn").textValue();
|
||||
|
||||
Response tagged = handler.handle("TagResource",
|
||||
(ObjectNode) parse("{\"resourceArn\":" + quoted(arn) + ",\"tags\":\"env=dev\"}"), REGION);
|
||||
assertEquals(400, tagged.getStatus());
|
||||
assertEquals("ValidationException", errorType(tagged));
|
||||
|
||||
Response untagged = handler.handle("UntagResource",
|
||||
(ObjectNode) parse("{\"resourceArn\":" + quoted(arn) + ",\"tagKeys\":\"env\"}"), REGION);
|
||||
assertEquals(400, untagged.getStatus());
|
||||
assertEquals("ValidationException", errorType(untagged));
|
||||
}
|
||||
|
||||
private JsonNode parse(String json) {
|
||||
try {
|
||||
return mapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("bad test fixture: " + json, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String quoted(String value) {
|
||||
return '"' + value + '"';
|
||||
}
|
||||
|
||||
private Response create(String namespaceName) {
|
||||
ObjectNode request = request("namespaceName", namespaceName);
|
||||
request.put("adminUsername", "admin");
|
||||
return handler.handle("CreateNamespace", request, REGION);
|
||||
}
|
||||
|
||||
private ObjectNode request(String field, String value) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
if (value != null) {
|
||||
request.put(field, value);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private JsonNode body(Response response) {
|
||||
assertEquals(200, response.getStatus(), "expected a successful response, got " + response.getEntity());
|
||||
return mapper.valueToTree(response.getEntity());
|
||||
}
|
||||
|
||||
private String errorType(Response response) {
|
||||
return mapper.valueToTree(response.getEntity()).path("__type").asText(null);
|
||||
}
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.redshiftserverless.model.Namespace;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessServiceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
|
||||
private RedshiftServerlessService service;
|
||||
private AccountAwareStorageBackend<Namespace> store;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
// A spy, not a plain in-memory backend: the in-memory store hands back the same object
|
||||
// reference a mutation already changed, so only an explicit write assertion can tell a
|
||||
// service that persists its change from one that merely mutated a shared instance. That
|
||||
// distinction is invisible under "memory" mode and load-bearing under "hybrid" and "wal".
|
||||
store = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAppliesAwsDefaultsAndAUniqueNamespaceId() {
|
||||
Namespace first = create("first-ns");
|
||||
Namespace second = create("second-ns");
|
||||
|
||||
assertEquals("dev", first.getDbName());
|
||||
assertEquals("AWS_OWNED_KMS_KEY", first.getKmsKeyId());
|
||||
assertEquals("AVAILABLE", first.getStatus());
|
||||
assertTrue(first.getLogExports().isEmpty());
|
||||
assertEquals("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":namespace/" + first.getNamespaceId(),
|
||||
first.getNamespaceArn());
|
||||
assertEquals(first.getNamespaceId(), UUID.fromString(first.getNamespaceId()).toString());
|
||||
assertNotEquals(first.getNamespaceId(), second.getNamespaceId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsADuplicateNamespaceName() {
|
||||
create("duplicate-ns");
|
||||
AwsException conflict = assertThrows(AwsException.class, () -> create("duplicate-ns"));
|
||||
assertEquals("ConflictException", conflict.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAndDeleteRejectAnUnknownNamespace() {
|
||||
assertEquals("ResourceNotFoundException",
|
||||
assertThrows(AwsException.class, () -> service.getNamespace("absent-ns", REGION)).getErrorCode());
|
||||
assertEquals("ResourceNotFoundException",
|
||||
assertThrows(AwsException.class, () -> service.deleteNamespace("absent-ns", REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePersistsOnlyTheSuppliedFields() {
|
||||
service.createNamespace("update-ns", "admin", "analytics", null, null,
|
||||
List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"), Map.of(), REGION);
|
||||
|
||||
service.updateNamespace("update-ns", null, "custom-key", null, List.of(), null, REGION);
|
||||
|
||||
Namespace reread = service.getNamespace("update-ns", REGION);
|
||||
assertEquals("custom-key", reread.getKmsKeyId());
|
||||
assertEquals("admin", reread.getAdminUsername());
|
||||
assertEquals("analytics", reread.getDbName());
|
||||
assertEquals(List.of("userlog"), reread.getLogExports());
|
||||
assertTrue(reread.getIamRoles().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteReportsDeletingAndRemovesTheNamespace() {
|
||||
create("delete-ns");
|
||||
assertEquals("DELETING", service.deleteNamespace("delete-ns", REGION).getStatus());
|
||||
assertThrows(AwsException.class, () -> service.getNamespace("delete-ns", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidNamespaceNamesAndLogExportsAreRejected() {
|
||||
assertEquals("ValidationException",
|
||||
assertThrows(AwsException.class, () -> create("Upper-Case")).getErrorCode());
|
||||
assertEquals("ValidationException",
|
||||
assertThrows(AwsException.class, () -> create("ab")).getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createNamespace("logs-ns", "admin", null, null, null, null,
|
||||
List.of("nosuchlog"), Map.of(), REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedWordNamespaceNamesAreRejectedByEveryOperation() {
|
||||
// "select" and "user" pass the length and [a-z0-9-] rules, so only the reserved-word
|
||||
// check can reject them. Asserting on create and on the read path as well, because
|
||||
// update and delete reach the validator through getNamespace.
|
||||
for (String reserved : List.of("select", "user")) {
|
||||
assertEquals("ValidationException",
|
||||
assertThrows(AwsException.class, () -> create(reserved)).getErrorCode());
|
||||
assertEquals("ValidationException",
|
||||
assertThrows(AwsException.class, () -> service.getNamespace(reserved, REGION)).getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.deleteNamespace(reserved, REGION)).getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.updateNamespace(reserved, null, "k", null, null, null, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
// A name that merely looks SQL-ish is not reserved and must still be accepted, and the
|
||||
// namespace must be readable back through a separate call rather than trusting create.
|
||||
create("analytics");
|
||||
assertEquals("analytics", service.getNamespace("analytics", REGION).getNamespaceName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIsScopedToTheRegionAndPaginates() {
|
||||
create("alpha-ns");
|
||||
create("beta-ns");
|
||||
service.createNamespace("gamma-ns", "admin", null, null, null, null, null, Map.of(), "us-west-2");
|
||||
|
||||
assertEquals(List.of("alpha-ns", "beta-ns"),
|
||||
service.listNamespaces(REGION, null, null).items().stream()
|
||||
.map(Namespace::getNamespaceName).toList());
|
||||
|
||||
var firstPage = service.listNamespaces(REGION, 1, null);
|
||||
assertEquals(List.of("alpha-ns"), firstPage.items().stream().map(Namespace::getNamespaceName).toList());
|
||||
assertEquals(List.of("beta-ns"), service.listNamespaces(REGION, 1, firstPage.nextToken()).items().stream()
|
||||
.map(Namespace::getNamespaceName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearRemovesPersistedState() {
|
||||
create("reset-ns");
|
||||
service.clear();
|
||||
assertTrue(service.listNamespaces(REGION, null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsSuppliedAtCreateAreReadableThroughListTagsForResource() {
|
||||
Namespace created = service.createNamespace("tagged-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), REGION);
|
||||
|
||||
assertEquals(Map.of("env", "dev"),
|
||||
service.listTagsForResource(created.getNamespaceArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResourceMergesAndUntagResourceRemovesByKey() {
|
||||
Namespace created = service.createNamespace("merge-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), REGION);
|
||||
String arn = created.getNamespaceArn();
|
||||
|
||||
service.tagResource(arn, Map.of("team", "data"), REGION);
|
||||
assertEquals(Map.of("env", "dev", "team", "data"), service.listTagsForResource(arn, REGION),
|
||||
"TagResource must merge: the pre-existing env tag has to survive a call that does not mention it");
|
||||
|
||||
service.tagResource(arn, Map.of("env", "prod"), REGION);
|
||||
assertEquals(Map.of("env", "prod", "team", "data"), service.listTagsForResource(arn, REGION));
|
||||
|
||||
service.untagResource(arn, List.of("env"), REGION);
|
||||
assertEquals(Map.of("team", "data"), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void taggingAnUnknownArnIsResourceNotFoundEvenWhenOtherNamespacesExist() {
|
||||
create("decoy-ns");
|
||||
create("second-decoy-ns");
|
||||
String absent = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID
|
||||
+ ":namespace/00000000-0000-0000-0000-000000000000";
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.listTagsForResource(absent, REGION)).getErrorCode());
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.tagResource(absent, Map.of("a", "b"), REGION)).getErrorCode());
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.untagResource(absent, List.of("a"), REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsSurviveAnUnrelatedNamespaceUpdate() {
|
||||
Namespace created = service.createNamespace("keep-tags-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), REGION);
|
||||
|
||||
service.updateNamespace("keep-tags-ns", null, "custom-key", null, null, null, REGION);
|
||||
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(created.getNamespaceArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnFromAnotherRegionIsNotTaggableFromThisOne() {
|
||||
Namespace elsewhere = service.createNamespace("west-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), "us-west-2");
|
||||
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.listTagsForResource(elsewhere.getNamespaceArn(), REGION)).getErrorCode());
|
||||
assertEquals(Map.of("env", "dev"),
|
||||
service.listTagsForResource(elsewhere.getNamespaceArn(), "us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagMutationsAreWrittenBackToStorage() {
|
||||
Namespace created = service.createNamespace("persist-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), REGION);
|
||||
String arn = created.getNamespaceArn();
|
||||
|
||||
clearInvocations(store);
|
||||
service.tagResource(arn, Map.of("team", "data"), REGION);
|
||||
verify(store).put(eq(REGION + "::persist-ns"), any(Namespace.class));
|
||||
|
||||
clearInvocations(store);
|
||||
service.untagResource(arn, List.of("team"), REGION);
|
||||
verify(store).put(eq(REGION + "::persist-ns"), any(Namespace.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStoresACopySoAReaderNeverSeesAHalfAppliedChange() {
|
||||
service.createNamespace("copy-ns", "admin", "analytics", null, null,
|
||||
List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"), Map.of(), REGION);
|
||||
Namespace readBeforeUpdate = service.getNamespace("copy-ns", REGION);
|
||||
|
||||
service.updateNamespace("copy-ns", "newadmin", "custom-key", null, List.of(), null, REGION);
|
||||
|
||||
Namespace readAfterUpdate = service.getNamespace("copy-ns", REGION);
|
||||
assertNotSame(readBeforeUpdate, readAfterUpdate, "update must store a new instance, not mutate the stored one");
|
||||
// The instance a concurrent reader was already holding is untouched, which is what makes
|
||||
// a torn read structurally impossible rather than merely unlikely.
|
||||
assertEquals("admin", readBeforeUpdate.getAdminUsername());
|
||||
assertEquals("AWS_OWNED_KMS_KEY", readBeforeUpdate.getKmsKeyId());
|
||||
assertEquals(List.of("arn:aws:iam::123456789012:role/one"), readBeforeUpdate.getIamRoles());
|
||||
assertEquals("newadmin", readAfterUpdate.getAdminUsername());
|
||||
assertEquals("custom-key", readAfterUpdate.getKmsKeyId());
|
||||
assertTrue(readAfterUpdate.getIamRoles().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagMutationsAlsoStoreACopy() {
|
||||
Namespace created = service.createNamespace("copy-tags-ns", "admin", null, null, null, null, null,
|
||||
Map.of("env", "dev"), REGION);
|
||||
Namespace readBeforeTagging = service.getNamespace("copy-tags-ns", REGION);
|
||||
|
||||
service.tagResource(created.getNamespaceArn(), Map.of("team", "data"), REGION);
|
||||
|
||||
Namespace readAfterTagging = service.getNamespace("copy-tags-ns", REGION);
|
||||
assertNotSame(readBeforeTagging, readAfterTagging);
|
||||
assertEquals(Map.of("env", "dev"), readBeforeTagging.getTags());
|
||||
assertEquals(Map.of("env", "dev", "team", "data"), readAfterTagging.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDoesNotMutateTheInstanceAReaderMayHold() {
|
||||
create("delete-copy-ns");
|
||||
Namespace readBeforeDelete = service.getNamespace("delete-copy-ns", REGION);
|
||||
|
||||
Namespace returned = service.deleteNamespace("delete-copy-ns", REGION);
|
||||
|
||||
assertEquals("DELETING", returned.getStatus());
|
||||
assertEquals("AVAILABLE", readBeforeDelete.getStatus(),
|
||||
"delete must not flip the status on an instance handed out by an earlier read");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCopyConstructorSharesNoMutableState() {
|
||||
Namespace original = service.createNamespace("copy-ctor-ns", "admin", null, null, null,
|
||||
List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"),
|
||||
Map.of("env", "dev"), REGION);
|
||||
|
||||
Namespace copy = new Namespace(original);
|
||||
copy.getIamRoles().add("arn:aws:iam::123456789012:role/two");
|
||||
copy.getLogExports().add("connectionlog");
|
||||
copy.getTags().put("team", "data");
|
||||
|
||||
assertEquals(List.of("arn:aws:iam::123456789012:role/one"), original.getIamRoles());
|
||||
assertEquals(List.of("userlog"), original.getLogExports());
|
||||
assertEquals(Map.of("env", "dev"), original.getTags());
|
||||
}
|
||||
|
||||
private Namespace create(String namespaceName) {
|
||||
return service.createNamespace(namespaceName, "admin", null, null, null, null, null, Map.of(), REGION);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user