firt commit

This commit is contained in:
Hector Ventura committed 2026-03-15 17:43:56 -05:00
commit 61433f59ab
313 files changed
+51266

No files matched your search

@@ -0,0 +1,212 @@
package io.github.hectorvent.floci.core.common;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration test verifying that data is isolated between regions.
* Uses different Authorization headers to simulate requests from different regions.
*/
@QuarkusTest
class RegionIsolationIntegrationTest {
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String AUTH_US_EAST_1 =
"AWS4-HMAC-SHA256 Credential=AKID/20260215/us-east-1/ssm/aws4_request, SignedHeaders=host, Signature=abc";
private static final String AUTH_US_WEST_2 =
"AWS4-HMAC-SHA256 Credential=AKID/20260215/us-west-2/ssm/aws4_request, SignedHeaders=host, Signature=abc";
private static final String AUTH_EU_WEST_1 =
"AWS4-HMAC-SHA256 Credential=AKID/20260215/eu-west-1/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
@BeforeAll
static void configureRestAssured() {
RestAssured.config = RestAssured.config().encoderConfig(
EncoderConfig.encoderConfig()
.encodeContentTypeAs(SSM_CONTENT_TYPE, ContentType.TEXT)
.encodeContentTypeAs(DYNAMODB_CONTENT_TYPE, ContentType.TEXT));
}
@Test
void ssmParametersAreIsolatedByRegion() {
// Put parameter in us-east-1
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.header("Authorization", AUTH_US_EAST_1)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/region-test/key", "Value": "east-value", "Type": "String"}
""")
.when().post("/")
.then().statusCode(200);
// Put same parameter name in us-west-2 with different value
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.header("Authorization", AUTH_US_WEST_2)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/region-test/key", "Value": "west-value", "Type": "String"}
""")
.when().post("/")
.then().statusCode(200);
// Get from us-east-1 — should return east-value
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.header("Authorization", AUTH_US_EAST_1)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/region-test/key"}
""")
.when().post("/")
.then()
.statusCode(200)
.body("Parameter.Value", equalTo("east-value"))
.body("Parameter.ARN", containsString("us-east-1"));
// Get from us-west-2 — should return west-value
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.header("Authorization", AUTH_US_WEST_2)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/region-test/key"}
""")
.when().post("/")
.then()
.statusCode(200)
.body("Parameter.Value", equalTo("west-value"))
.body("Parameter.ARN", containsString("us-west-2"));
}
@Test
void dynamoDbTablesAreIsolatedByRegion() {
// Create table in us-east-1
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.header("Authorization", AUTH_US_EAST_1)
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "RegionTestTable",
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
"ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}
}
""")
.when().post("/")
.then()
.statusCode(200)
.body("TableDescription.TableArn", containsString("us-east-1"));
// Create same table name in eu-west-1 — should succeed (different region)
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.header("Authorization", AUTH_EU_WEST_1)
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "RegionTestTable",
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
"ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}
}
""")
.when().post("/")
.then()
.statusCode(200)
.body("TableDescription.TableArn", containsString("eu-west-1"));
// List tables in us-east-1 — should see RegionTestTable
given()
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
.header("Authorization", AUTH_US_EAST_1)
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.body("TableNames", hasItem("RegionTestTable"));
// List tables in us-west-2 (no tables created there) — should NOT see RegionTestTable
given()
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
.header("Authorization", AUTH_US_WEST_2)
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.body("TableNames", not(hasItem("RegionTestTable")));
}
@Test
void sqsQueuesAreIsolatedByRegion() {
// Create queue in us-east-1
given()
.header("Authorization", AUTH_US_EAST_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "region-test-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("region-test-queue"));
// Create same queue name in us-west-2 — should succeed (different region)
given()
.header("Authorization", AUTH_US_WEST_2)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "region-test-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("region-test-queue"));
// List queues in us-east-1 — should see it
given()
.header("Authorization", AUTH_US_EAST_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("region-test-queue"));
}
@Test
void defaultRegionUsedWhenNoAuthHeader() {
// Request without Authorization header falls back to default (us-east-1)
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/default-region-test", "Value": "default", "Type": "String"}
""")
.when().post("/")
.then().statusCode(200);
// Can retrieve with explicit us-east-1 auth
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.header("Authorization", AUTH_US_EAST_1)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/default-region-test"}
""")
.when().post("/")
.then()
.statusCode(200)
.body("Parameter.Value", equalTo("default"));
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Cookie;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class RegionResolverTest {
private final RegionResolver resolver = new RegionResolver("us-east-1", "000000000000");
@Test
void resolveRegionFromAuthorizationHeader() {
HttpHeaders headers = stubHeaders(
"AWS4-HMAC-SHA256 Credential=AKID/20260215/us-west-2/s3/aws4_request, " +
"SignedHeaders=host, Signature=abc123");
assertEquals("us-west-2", resolver.resolveRegion(headers));
}
@Test
void resolveRegionFromDifferentRegion() {
HttpHeaders headers = stubHeaders(
"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20260215/eu-west-1/sqs/aws4_request, " +
"SignedHeaders=host, Signature=xyz");
assertEquals("eu-west-1", resolver.resolveRegion(headers));
}
@Test
void fallsBackToDefaultWhenNoAuthHeader() {
HttpHeaders headers = stubHeaders(null);
assertEquals("us-east-1", resolver.resolveRegion(headers));
}
@Test
void fallsBackToDefaultWhenEmptyAuthHeader() {
HttpHeaders headers = stubHeaders("");
assertEquals("us-east-1", resolver.resolveRegion(headers));
}
@Test
void fallsBackToDefaultWhenNullHeaders() {
assertEquals("us-east-1", resolver.resolveRegion(null));
}
@Test
void fallsBackToDefaultWhenMalformedAuthHeader() {
HttpHeaders headers = stubHeaders("Bearer some-token");
assertEquals("us-east-1", resolver.resolveRegion(headers));
}
@Test
void getAccountId() {
assertEquals("000000000000", resolver.getAccountId());
}
@Test
void buildArn() {
assertEquals("arn:aws:ssm:us-west-2:000000000000:parameter/myParam",
resolver.buildArn("ssm", "us-west-2", "parameter/myParam"));
}
@Test
void customDefaultRegionAndAccountId() {
RegionResolver custom = new RegionResolver("ap-southeast-1", "123456789012");
assertEquals("ap-southeast-1", custom.getDefaultRegion());
assertEquals("123456789012", custom.getAccountId());
assertEquals("ap-southeast-1", custom.resolveRegion(null));
}
private static HttpHeaders stubHeaders(String authorizationValue) {
return new HttpHeaders() {
@Override public List<String> getRequestHeader(String name) {
if ("Authorization".equalsIgnoreCase(name) && authorizationValue != null) {
return List.of(authorizationValue);
}
return List.of();
}
@Override public String getHeaderString(String name) {
if ("Authorization".equalsIgnoreCase(name)) return authorizationValue;
return null;
}
@Override public MultivaluedMap<String, String> getRequestHeaders() { return new MultivaluedHashMap<>(); }
@Override public List<MediaType> getAcceptableMediaTypes() { return List.of(); }
@Override public List<Locale> getAcceptableLanguages() { return List.of(); }
@Override public MediaType getMediaType() { return null; }
@Override public Locale getLanguage() { return null; }
@Override public Map<String, Cookie> getCookies() { return Map.of(); }
@Override public Date getDate() { return null; }
@Override public int getLength() { return 0; }
};
}
}
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.core.common.port;
import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.*;
class PortAllocatorTest {
@Test
void allocatesSequentiallyFromBase() {
PortAllocator allocator = new PortAllocator(9200, 9299);
assertEquals(9200, allocator.allocate());
assertEquals(9201, allocator.allocate());
assertEquals(9202, allocator.allocate());
}
@Test
void concurrentAllocationsAreUnique() throws InterruptedException {
PortAllocator allocator = new PortAllocator(9200, 9299);
int threads = 50;
Set<Integer> ports = ConcurrentHashMap.newKeySet();
CountDownLatch latch = new CountDownLatch(threads);
ExecutorService executor = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
executor.submit(() -> {
ports.add(allocator.allocate());
latch.countDown();
});
}
latch.await();
executor.shutdown();
assertEquals(threads, ports.size(), "All allocated ports must be unique");
}
}
@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class HybridStorageTest {
@TempDir
Path tempDir;
private HybridStorage<String, String> storage;
@BeforeEach
void setUp() {
Path filePath = tempDir.resolve("hybrid-test.json");
storage = new HybridStorage<>(filePath, new TypeReference<>() {
}, 60000);
}
@AfterEach
void tearDown() {
storage.shutdown();
}
@Test
void putAndGetFromMemory() {
storage.put("key1", "value1");
assertEquals("value1", storage.get("key1").orElseThrow());
}
@Test
void explicitFlushPersistsData() {
Path filePath = tempDir.resolve("flush-test.json");
var store1 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
store1.put("key1", "value1");
store1.flush();
store1.shutdown();
var store2 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
store2.load();
assertEquals("value1", store2.get("key1").orElseThrow());
store2.shutdown();
}
@Test
void deleteRemovesFromMemory() {
storage.put("key1", "value1");
storage.delete("key1");
assertTrue(storage.get("key1").isEmpty());
}
@Test
void scanWorks() {
storage.put("a.1", "v1");
storage.put("a.2", "v2");
storage.put("b.1", "v3");
var results = storage.scan(key -> key.startsWith("a."));
assertEquals(2, results.size());
}
@Test
void clearRemovesAll() {
storage.put("key1", "value1");
storage.put("key2", "value2");
storage.clear();
assertTrue(storage.get("key1").isEmpty());
assertTrue(storage.get("key2").isEmpty());
}
}
@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.core.storage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class InMemoryStorageTest {
private InMemoryStorage<String, String> storage;
@BeforeEach
void setUp() {
storage = new InMemoryStorage<>();
}
@Test
void putAndGet() {
storage.put("key1", "value1");
Optional<String> result = storage.get("key1");
assertTrue(result.isPresent());
assertEquals("value1", result.get());
}
@Test
void getReturnsEmptyForMissingKey() {
assertTrue(storage.get("missing").isEmpty());
}
@Test
void putOverwritesExistingValue() {
storage.put("key1", "value1");
storage.put("key1", "value2");
assertEquals("value2", storage.get("key1").orElseThrow());
}
@Test
void delete() {
storage.put("key1", "value1");
storage.delete("key1");
assertTrue(storage.get("key1").isEmpty());
}
@Test
void deleteNonExistentKeyDoesNotThrow() {
assertDoesNotThrow(() -> storage.delete("missing"));
}
@Test
void scan() {
storage.put("app.db.host", "localhost");
storage.put("app.db.port", "5432");
storage.put("app.cache.host", "redis");
List<String> dbValues = storage.scan(key -> key.startsWith("app.db."));
assertEquals(2, dbValues.size());
assertTrue(dbValues.contains("localhost"));
assertTrue(dbValues.contains("5432"));
}
@Test
void scanWithNoMatchesReturnsEmptyList() {
storage.put("key1", "value1");
List<String> result = storage.scan(key -> key.startsWith("nonexistent"));
assertTrue(result.isEmpty());
}
@Test
void clear() {
storage.put("key1", "value1");
storage.put("key2", "value2");
storage.clear();
assertTrue(storage.get("key1").isEmpty());
assertTrue(storage.get("key2").isEmpty());
}
@Test
void flushAndLoadAreNoOps() {
storage.put("key1", "value1");
assertDoesNotThrow(() -> storage.flush());
assertDoesNotThrow(() -> storage.load());
assertEquals("value1", storage.get("key1").orElseThrow());
}
}
@@ -0,0 +1,74 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class PersistentStorageTest {
@TempDir
Path tempDir;
private PersistentStorage<String, String> storage;
@BeforeEach
void setUp() {
Path filePath = tempDir.resolve("test-store.json");
storage = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
}
@Test
void putAndGet() {
storage.put("key1", "value1");
assertEquals("value1", storage.get("key1").orElseThrow());
}
@Test
void persistsAcrossInstances() {
Path filePath = tempDir.resolve("persist-test.json");
var store1 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
store1.put("key1", "value1");
store1.put("key2", "value2");
var store2 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
store2.load();
assertEquals("value1", store2.get("key1").orElseThrow());
assertEquals("value2", store2.get("key2").orElseThrow());
}
@Test
void delete() {
storage.put("key1", "value1");
storage.delete("key1");
assertTrue(storage.get("key1").isEmpty());
}
@Test
void scan() {
storage.put("/app/db/host", "localhost");
storage.put("/app/db/port", "5432");
storage.put("/app/cache/host", "redis");
List<String> results = storage.scan(key -> key.startsWith("/app/db/"));
assertEquals(2, results.size());
}
@Test
void clear() {
storage.put("key1", "value1");
storage.clear();
assertTrue(storage.get("key1").isEmpty());
}
@Test
void loadFromEmptyFileDoesNotThrow() {
assertDoesNotThrow(() -> storage.load());
}
}
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class WalStorageTest {
@TempDir
Path tempDir;
private WalStorage<String, String> storage;
@BeforeEach
void setUp() {
Path snapshotPath = tempDir.resolve("snapshot.json");
Path walPath = tempDir.resolve("data.wal");
storage = new WalStorage<>(snapshotPath, walPath, new TypeReference<>() {}, 60000);
storage.load();
}
@AfterEach
void tearDown() {
storage.shutdown();
}
@Test
void putAndGet() {
storage.put("key1", "value1");
assertEquals("value1", storage.get("key1").orElseThrow());
}
@Test
void getReturnsEmptyForMissingKey() {
assertTrue(storage.get("nonexistent").isEmpty());
}
@Test
void deleteRemovesEntry() {
storage.put("key1", "value1");
storage.delete("key1");
assertTrue(storage.get("key1").isEmpty());
}
@Test
void scanWithPredicate() {
storage.put("a.1", "v1");
storage.put("a.2", "v2");
storage.put("b.1", "v3");
var results = storage.scan(key -> key.startsWith("a."));
assertEquals(2, results.size());
}
@Test
void clearRemovesAllEntries() {
storage.put("key1", "value1");
storage.put("key2", "value2");
storage.clear();
assertTrue(storage.get("key1").isEmpty());
assertTrue(storage.get("key2").isEmpty());
}
@Test
void flushAndLoadRestoresData() {
Path snapshotPath = tempDir.resolve("persist-snapshot.json");
Path walPath = tempDir.resolve("persist-data.wal");
var store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 60000);
store1.load();
store1.put("key1", "value1");
store1.put("key2", "value2");
store1.flush();
store1.shutdown();
var store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 60000);
store2.load();
assertEquals("value1", store2.get("key1").orElseThrow());
assertEquals("value2", store2.get("key2").orElseThrow());
store2.shutdown();
}
@Test
void walReplayRestoresUncompactedWrites() {
Path snapshotPath = tempDir.resolve("replay-snapshot.json");
Path walPath = tempDir.resolve("replay-data.wal");
var store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store1.load();
store1.put("key1", "value1");
store1.put("key2", "value2");
store1.delete("key1");
// Load a second instance from the same WAL (before compaction)
var store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
assertTrue(store2.get("key1").isEmpty());
assertEquals("value2", store2.get("key2").orElseThrow());
store1.shutdown();
store2.shutdown();
}
@Test
void walWritesBinaryFormat() throws IOException {
Path walPath = tempDir.resolve("binary-check.wal");
Path snapshotPath = tempDir.resolve("binary-check-snapshot.json");
var store = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store.load();
store.put("k", "v");
store.delete("d");
// Read raw binary WAL and verify structure (CBOR-encoded payloads)
ObjectMapper cborMapper = new ObjectMapper(new CBORFactory());
try (DataInputStream in = new DataInputStream(Files.newInputStream(walPath))) {
// First entry: PUT
assertEquals(WalStorage.OP_PUT, in.readByte());
int keyLen = in.readInt();
assertTrue(keyLen > 0);
byte[] keyBytes = in.readNBytes(keyLen);
// CBOR short string "k" starts with 0x61 (major type 3, length 1)
assertEquals((byte) 0x61, keyBytes[0], "CBOR string type byte expected");
assertEquals("k", cborMapper.readValue(keyBytes, String.class));
int valueLen = in.readInt();
assertTrue(valueLen > 0);
byte[] valueBytes = in.readNBytes(valueLen);
assertEquals((byte) 0x61, valueBytes[0], "CBOR string type byte expected");
assertEquals("v", cborMapper.readValue(valueBytes, String.class));
// Second entry: DELETE
assertEquals(WalStorage.OP_DELETE, in.readByte());
int delKeyLen = in.readInt();
byte[] delKeyBytes = in.readNBytes(delKeyLen);
assertEquals((byte) 0x61, delKeyBytes[0], "CBOR string type byte expected");
assertEquals("d", cborMapper.readValue(delKeyBytes, String.class));
// No more data
assertEquals(0, in.available());
}
store.shutdown();
}
@Test
void truncatedWalEntryIsSkippedGracefully() throws IOException {
Path walPath = tempDir.resolve("truncated.wal");
Path snapshotPath = tempDir.resolve("truncated-snapshot.json");
var store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store1.load();
store1.put("good", "data");
store1.put("another", "entry");
// Truncate the WAL file mid-entry (chop off last few bytes)
long walSize = Files.size(walPath);
try (RandomAccessFile raf = new RandomAccessFile(walPath.toFile(), "rw")) {
raf.setLength(walSize - 3);
}
// Load a new instance — should recover the first complete entry
var store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
assertEquals("data", store2.get("good").orElseThrow());
// The truncated second entry may or may not be recovered depending on where truncation hit
store1.shutdown();
store2.shutdown();
}
}
@@ -0,0 +1,339 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayIntegrationTest {
private static String apiId;
private static String rootId;
private static String resourceId;
private static String deploymentId;
// ──────────────────────────── REST API lifecycle ────────────────────────────
@Test @Order(1)
void createRestApi() {
String body = """
{"name":"test-api","description":"Integration test API"}
""";
apiId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("name", equalTo("test-api"))
.body("description", equalTo("Integration test API"))
.extract().path("id");
}
@Test @Order(2)
void getRestApi() {
given()
.when().get("/restapis/" + apiId)
.then()
.statusCode(200)
.body("id", equalTo(apiId))
.body("name", equalTo("test-api"));
}
@Test @Order(3)
void listRestApis() {
given()
.when().get("/restapis")
.then()
.statusCode(200)
.body("item.id", hasItem(apiId));
}
@Test @Order(4)
void getRestApiNotFound() {
given()
.when().get("/restapis/doesnotexist")
.then()
.statusCode(404);
}
// ──────────────────────────── Resources ────────────────────────────
@Test @Order(5)
void getRootResource() {
rootId = given()
.when().get("/restapis/" + apiId + "/resources")
.then()
.statusCode(200)
.body("item", hasSize(1))
.body("item[0].path", equalTo("/"))
.extract().path("item[0].id");
}
@Test @Order(6)
void createResource() {
resourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"users\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then()
.statusCode(201)
.body("id", notNullValue())
.body("path", equalTo("/users"))
.body("pathPart", equalTo("users"))
.extract().path("id");
}
@Test @Order(7)
void getResource() {
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId)
.then()
.statusCode(200)
.body("path", equalTo("/users"));
}
// ──────────────────────────── Methods ────────────────────────────
@Test @Order(8)
void putMethod() {
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then()
.statusCode(201)
.body("httpMethod", equalTo("GET"))
.body("authorizationType", equalTo("NONE"));
}
@Test @Order(9)
void putMethodResponse() {
given()
.contentType(ContentType.JSON)
.body("{\"responseParameters\":{}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")
.then()
.statusCode(201)
.body("statusCode", equalTo("200"));
}
@Test @Order(10)
void getMethodResponse() {
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")
.then()
.statusCode(200)
.body("statusCode", equalTo("200"));
}
// ──────────────────────────── Integration ────────────────────────────
@Test @Order(11)
void putIntegration() {
String body = """
{"type":"MOCK","requestTemplates":{"application/json":"{\\"statusCode\\": 200}"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then()
.statusCode(201)
.body("type", equalTo("MOCK"));
}
@Test @Order(12)
void getIntegration() {
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then()
.statusCode(200)
.body("type", equalTo("MOCK"));
}
@Test @Order(13)
void putIntegrationResponse() {
String body = """
{"selectionPattern":"","responseTemplates":{"application/json":""}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/GET/integration/responses/200")
.then()
.statusCode(201)
.body("statusCode", equalTo("200"));
}
@Test @Order(14)
void getIntegrationResponse() {
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/GET/integration/responses/200")
.then()
.statusCode(200)
.body("statusCode", equalTo("200"));
}
@Test @Order(15)
void getMethodHasIntegration() {
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then()
.statusCode(200)
.body("methodIntegration.type", equalTo("MOCK"));
}
// ──────────────────────────── Deployments ────────────────────────────
@Test @Order(16)
void createDeployment() {
deploymentId = given()
.contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("description", equalTo("v1"))
.extract().path("id");
}
@Test @Order(17)
void getDeployments() {
given()
.when().get("/restapis/" + apiId + "/deployments")
.then()
.statusCode(200)
.body("item.id", hasItem(deploymentId));
}
// ──────────────────────────── Stages ────────────────────────────
@Test @Order(18)
void createStage() {
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"prod\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then()
.statusCode(201)
.body("stageName", equalTo("prod"))
.body("deploymentId", equalTo(deploymentId));
}
@Test @Order(19)
void getStage() {
given()
.when().get("/restapis/" + apiId + "/stages/prod")
.then()
.statusCode(200)
.body("stageName", equalTo("prod"));
}
@Test @Order(20)
void listStages() {
given()
.when().get("/restapis/" + apiId + "/stages")
.then()
.statusCode(200)
.body("item.stageName", hasItem("prod"));
}
@Test @Order(21)
void updateStage() {
String patch = """
{"patchOperations":[{"op":"replace","path":"/description","value":"Production"}]}
""";
given()
.contentType(ContentType.JSON)
.body(patch)
.when().patch("/restapis/" + apiId + "/stages/prod")
.then()
.statusCode(200)
.body("description", equalTo("Production"));
}
// ──────────────────────────── Tags ────────────────────────────
@Test @Order(22)
void tagResource() {
String arn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId;
given()
.contentType(ContentType.JSON)
.body("{\"tags\":{\"env\":\"test\"}}")
.when().put("/tags/" + arn)
.then()
.statusCode(204);
}
@Test @Order(23)
void getTags() {
String arn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId;
given()
.when().get("/tags/" + arn)
.then()
.statusCode(200)
.body("tags.env", equalTo("test"));
}
@Test @Order(24)
void untagResource() {
String arn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId;
given()
.queryParam("tagKeys", "env")
.when().delete("/tags/" + arn)
.then()
.statusCode(204);
given()
.when().get("/tags/" + arn)
.then()
.statusCode(200)
.body("tags.env", nullValue());
}
// ──────────────────────────── Cleanup ────────────────────────────
@Test @Order(25)
void deleteStage() {
given()
.when().delete("/restapis/" + apiId + "/stages/prod")
.then()
.statusCode(202);
}
@Test @Order(26)
void deleteResource() {
given()
.when().delete("/restapis/" + apiId + "/resources/" + resourceId)
.then()
.statusCode(204);
}
@Test @Order(27)
void deleteRestApi() {
given()
.when().delete("/restapis/" + apiId)
.then()
.statusCode(202);
}
@Test @Order(28)
void getDeletedRestApiReturns404() {
given()
.when().get("/restapis/" + apiId)
.then()
.statusCode(404);
}
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
class CloudFormationIntegrationTest {
@Test
void createStack_withS3AndSqs() {
String template = """
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "cf-test-bucket"
}
},
"MyQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "cf-test-queue"
}
}
}
}
""";
// 1. Create Stack
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "test-stack")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
// 2. Verify S3 Bucket exists
given()
.header("Host", "cf-test-bucket.localhost")
.when()
.get("/")
.then()
.statusCode(200);
// 3. Verify SQS Queue exists
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", "cf-test-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("cf-test-queue"));
// 4. Describe Stacks
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", "test-stack")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackName>test-stack</StackName>"))
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
}
}
@@ -0,0 +1,266 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class CloudWatchLogsServiceTest {
private static final String REGION = "us-east-1";
private CloudWatchLogsService service;
@BeforeEach
void setUp() {
service = new CloudWatchLogsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10000,
new RegionResolver("us-east-1", "000000000000")
);
}
// ──────────────────────────── Log Groups ────────────────────────────
@Test
void createLogGroup() {
service.createLogGroup("/app/logs", null, null, REGION);
List<LogGroup> groups = service.describeLogGroups(null, REGION);
assertEquals(1, groups.size());
assertEquals("/app/logs", groups.getFirst().getLogGroupName());
}
@Test
void createLogGroupDuplicateThrows() {
service.createLogGroup("/app/logs", null, null, REGION);
assertThrows(AwsException.class, () ->
service.createLogGroup("/app/logs", null, null, REGION));
}
@Test
void createLogGroupBlankNameThrows() {
assertThrows(AwsException.class, () ->
service.createLogGroup("", null, null, REGION));
}
@Test
void deleteLogGroup() {
service.createLogGroup("/app/logs", null, null, REGION);
service.deleteLogGroup("/app/logs", REGION);
assertTrue(service.describeLogGroups(null, REGION).isEmpty());
}
@Test
void deleteLogGroupNotFoundThrows() {
assertThrows(AwsException.class, () ->
service.deleteLogGroup("/missing", REGION));
}
@Test
void describeLogGroupsWithPrefix() {
service.createLogGroup("/app/alpha", null, null, REGION);
service.createLogGroup("/app/beta", null, null, REGION);
service.createLogGroup("/other/logs", null, null, REGION);
List<LogGroup> result = service.describeLogGroups("/app", REGION);
assertEquals(2, result.size());
}
@Test
void putAndDeleteRetentionPolicy() {
service.createLogGroup("/app/logs", null, null, REGION);
service.putRetentionPolicy("/app/logs", 30, REGION);
LogGroup group = service.describeLogGroups("/app/logs", REGION).getFirst();
assertEquals(30, group.getRetentionInDays());
service.deleteRetentionPolicy("/app/logs", REGION);
group = service.describeLogGroups("/app/logs", REGION).getFirst();
assertNull(group.getRetentionInDays());
}
@Test
void tagAndUntagLogGroup() {
service.createLogGroup("/app/logs", null, Map.of("env", "prod"), REGION);
service.tagLogGroup("/app/logs", Map.of("team", "platform"), REGION);
Map<String, String> tags = service.listTagsLogGroup("/app/logs", REGION);
assertEquals("prod", tags.get("env"));
assertEquals("platform", tags.get("team"));
service.untagLogGroup("/app/logs", List.of("env"), REGION);
tags = service.listTagsLogGroup("/app/logs", REGION);
assertFalse(tags.containsKey("env"));
}
// ──────────────────────────── Log Streams ────────────────────────────
@Test
void createLogStream() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
List<LogStream> streams = service.describeLogStreams("/app/logs", null, REGION);
assertEquals(1, streams.size());
assertEquals("stream-1", streams.getFirst().getLogStreamName());
}
@Test
void createLogStreamForNonExistentGroupThrows() {
assertThrows(AwsException.class, () ->
service.createLogStream("/missing", "stream-1", REGION));
}
@Test
void createLogStreamDuplicateThrows() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
assertThrows(AwsException.class, () ->
service.createLogStream("/app/logs", "stream-1", REGION));
}
@Test
void deleteLogStream() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
service.deleteLogStream("/app/logs", "stream-1", REGION);
assertTrue(service.describeLogStreams("/app/logs", null, REGION).isEmpty());
}
@Test
void deleteLogGroupCascadesStreamsAndEvents() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
service.putLogEvents("/app/logs", "stream-1",
List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "hello")), REGION);
service.deleteLogGroup("/app/logs", REGION);
assertTrue(service.describeLogGroups(null, REGION).isEmpty());
}
// ──────────────────────────── Log Events ────────────────────────────
@Test
void putAndGetLogEvents() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
long now = System.currentTimeMillis();
service.putLogEvents("/app/logs", "stream-1", List.of(
Map.of("timestamp", now, "message", "first"),
Map.of("timestamp", now + 1, "message", "second")
), REGION);
CloudWatchLogsService.LogEventsResult result = service.getLogEvents(
"/app/logs", "stream-1", null, null, 100, true, REGION);
assertEquals(2, result.events().size());
assertEquals("first", result.events().get(0).getMessage());
assertEquals("second", result.events().get(1).getMessage());
}
@Test
void getLogEventsWithTimeRange() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
long base = System.currentTimeMillis();
service.putLogEvents("/app/logs", "stream-1", List.of(
Map.of("timestamp", base, "message", "old"),
Map.of("timestamp", base + 10000, "message", "new")
), REGION);
CloudWatchLogsService.LogEventsResult result = service.getLogEvents(
"/app/logs", "stream-1", base + 5000, null, 100, true, REGION);
assertEquals(1, result.events().size());
assertEquals("new", result.events().getFirst().getMessage());
}
@Test
void filterLogEvents() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
long now = System.currentTimeMillis();
service.putLogEvents("/app/logs", "stream-1", List.of(
Map.of("timestamp", now, "message", "ERROR: something failed"),
Map.of("timestamp", now + 1, "message", "INFO: all good"),
Map.of("timestamp", now + 2, "message", "ERROR: another failure")
), REGION);
CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents(
"/app/logs", null, null, null, "ERROR", 100, REGION);
assertEquals(2, result.events().size());
assertTrue(result.events().stream().allMatch(e -> e.getMessage().contains("ERROR")));
}
@Test
void filterLogEventsNoPattern() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
long now = System.currentTimeMillis();
service.putLogEvents("/app/logs", "stream-1", List.of(
Map.of("timestamp", now, "message", "msg1"),
Map.of("timestamp", now + 1, "message", "msg2")
), REGION);
CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents(
"/app/logs", null, null, null, null, 100, REGION);
assertEquals(2, result.events().size());
}
@Test
void putLogEventsUpdatesStreamMetadata() {
service.createLogGroup("/app/logs", null, null, REGION);
service.createLogStream("/app/logs", "stream-1", REGION);
long now = System.currentTimeMillis();
service.putLogEvents("/app/logs", "stream-1",
List.of(Map.of("timestamp", now, "message", "test")), REGION);
List<LogStream> streams = service.describeLogStreams("/app/logs", null, REGION);
LogStream stream = streams.getFirst();
assertEquals(now, stream.getFirstEventTimestamp());
assertEquals(now, stream.getLastEventTimestamp());
assertNotNull(stream.getLastIngestionTime());
}
@Test
void maxEventsPerQueryIsRespected() {
CloudWatchLogsService limitedService = new CloudWatchLogsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
2,
new RegionResolver("us-east-1", "000000000000")
);
limitedService.createLogGroup("/app/logs", null, null, REGION);
limitedService.createLogStream("/app/logs", "stream-1", REGION);
long now = System.currentTimeMillis();
limitedService.putLogEvents("/app/logs", "stream-1", List.of(
Map.of("timestamp", now, "message", "a"),
Map.of("timestamp", now + 1, "message", "b"),
Map.of("timestamp", now + 2, "message", "c")
), REGION);
CloudWatchLogsService.LogEventsResult result = limitedService.getLogEvents(
"/app/logs", "stream-1", null, null, 100, true, REGION);
assertEquals(2, result.events().size());
}
}
@@ -0,0 +1,222 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CloudWatchMetricsServiceTest {
private static final String REGION = "us-east-1";
private static final String NAMESPACE = "MyApp/Metrics";
private CloudWatchMetricsService service;
@BeforeEach
void setUp() {
service = new CloudWatchMetricsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000")
);
}
private MetricDatum datum(String name, double value) {
MetricDatum d = new MetricDatum();
d.setMetricName(name);
d.setValue(value);
return d;
}
private MetricDatum datumWithDimension(String name, double value, String dimName, String dimValue) {
MetricDatum d = datum(name, value);
d.setDimensions(List.of(new Dimension(dimName, dimValue)));
return d;
}
// ──────────────────────────── PutMetricData / ListMetrics ────────────────────────────
@Test
void putMetricDataAndList() {
service.putMetricData(NAMESPACE, List.of(datum("RequestCount", 42)), REGION);
List<CloudWatchMetricsService.MetricIdentity> metrics = service.listMetrics(NAMESPACE, null, null, REGION);
assertEquals(1, metrics.size());
assertEquals("RequestCount", metrics.getFirst().metricName());
assertEquals(NAMESPACE, metrics.getFirst().namespace());
}
@Test
void listMetricsDeduplicates() {
service.putMetricData(NAMESPACE, List.of(datum("RequestCount", 1)), REGION);
service.putMetricData(NAMESPACE, List.of(datum("RequestCount", 2)), REGION);
List<CloudWatchMetricsService.MetricIdentity> metrics = service.listMetrics(NAMESPACE, null, null, REGION);
assertEquals(1, metrics.size());
}
@Test
void listMetricsFilterByName() {
service.putMetricData(NAMESPACE, List.of(datum("RequestCount", 1), datum("ErrorCount", 1)), REGION);
List<CloudWatchMetricsService.MetricIdentity> result = service.listMetrics(NAMESPACE, "ErrorCount", null, REGION);
assertEquals(1, result.size());
assertEquals("ErrorCount", result.getFirst().metricName());
}
@Test
void listMetricsFilterByDimension() {
service.putMetricData(NAMESPACE, List.of(
datumWithDimension("Latency", 100, "Service", "auth"),
datumWithDimension("Latency", 200, "Service", "api")
), REGION);
List<CloudWatchMetricsService.MetricIdentity> result = service.listMetrics(
NAMESPACE, "Latency", List.of(new Dimension("Service", "auth")), REGION);
assertEquals(1, result.size());
}
@Test
void putMetricDataAutoFillsStatistics() {
service.putMetricData(NAMESPACE, List.of(datum("Requests", 5.0)), REGION);
Instant start = Instant.now().minusSeconds(60);
Instant end = Instant.now().plusSeconds(60);
List<CloudWatchMetricsService.Datapoint> points = service.getMetricStatistics(
NAMESPACE, "Requests", null, start, end, 60, List.of("Sum"), null, REGION);
assertFalse(points.isEmpty());
assertEquals(5.0, points.getFirst().sum());
assertEquals(1.0, points.getFirst().sampleCount());
}
// ──────────────────────────── GetMetricStatistics ────────────────────────────
@Test
void getMetricStatisticsBucketsByPeriod() {
long now = Instant.now().getEpochSecond();
long bucket1 = (now / 60) * 60;
long bucket2 = bucket1 + 60;
MetricDatum d1 = datum("Requests", 10);
d1.setTimestamp(bucket1);
MetricDatum d2 = datum("Requests", 20);
d2.setTimestamp(bucket2);
service.putMetricData(NAMESPACE, List.of(d1, d2), REGION);
List<CloudWatchMetricsService.Datapoint> points = service.getMetricStatistics(
NAMESPACE, "Requests", null,
Instant.ofEpochSecond(bucket1 - 1),
Instant.ofEpochSecond(bucket2 + 1),
60, List.of("Sum"), null, REGION);
assertEquals(2, points.size());
}
@Test
void getMetricStatisticsReturnsEmptyOutsideRange() {
MetricDatum d = datum("Requests", 10);
d.setTimestamp(Instant.now().minusSeconds(7200).getEpochSecond());
service.putMetricData(NAMESPACE, List.of(d), REGION);
List<CloudWatchMetricsService.Datapoint> result = service.getMetricStatistics(
NAMESPACE, "Requests", null,
Instant.now().minusSeconds(60),
Instant.now(),
60, List.of("Sum"), null, REGION);
assertTrue(result.isEmpty());
}
// ──────────────────────────── Alarms ────────────────────────────
@Test
void putAndDescribeAlarm() {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("high-error-rate");
alarm.setMetricName("ErrorCount");
alarm.setNamespace(NAMESPACE);
service.putMetricAlarm(alarm, REGION);
List<MetricAlarm> alarms = service.describeAlarms(null, null, REGION);
assertEquals(1, alarms.size());
assertEquals("high-error-rate", alarms.getFirst().getAlarmName());
assertNotNull(alarms.getFirst().getAlarmArn());
}
@Test
void describeAlarmsByName() {
MetricAlarm a1 = new MetricAlarm();
a1.setAlarmName("alarm-1");
MetricAlarm a2 = new MetricAlarm();
a2.setAlarmName("alarm-2");
service.putMetricAlarm(a1, REGION);
service.putMetricAlarm(a2, REGION);
List<MetricAlarm> result = service.describeAlarms(List.of("alarm-1"), null, REGION);
assertEquals(1, result.size());
assertEquals("alarm-1", result.getFirst().getAlarmName());
}
@Test
void describeAlarmsByPrefix() {
MetricAlarm a1 = new MetricAlarm();
a1.setAlarmName("prod-errors");
MetricAlarm a2 = new MetricAlarm();
a2.setAlarmName("prod-latency");
MetricAlarm a3 = new MetricAlarm();
a3.setAlarmName("dev-errors");
service.putMetricAlarm(a1, REGION);
service.putMetricAlarm(a2, REGION);
service.putMetricAlarm(a3, REGION);
List<MetricAlarm> result = service.describeAlarms(null, "prod-", REGION);
assertEquals(2, result.size());
}
@Test
void deleteAlarms() {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("to-delete");
service.putMetricAlarm(alarm, REGION);
service.deleteAlarms(List.of("to-delete"), REGION);
assertTrue(service.describeAlarms(null, null, REGION).isEmpty());
}
@Test
void setAlarmState() {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("my-alarm");
service.putMetricAlarm(alarm, REGION);
service.setAlarmState("my-alarm", "ALARM", "Threshold breached", null, REGION);
MetricAlarm updated = service.describeAlarms(List.of("my-alarm"), null, REGION).getFirst();
assertEquals("ALARM", updated.getStateValue());
assertEquals("Threshold breached", updated.getStateReason());
}
@Test
void buildDimKeyIsDeterministic() {
List<Dimension> dims1 = List.of(new Dimension("B", "2"), new Dimension("A", "1"));
List<Dimension> dims2 = List.of(new Dimension("A", "1"), new Dimension("B", "2"));
assertEquals(CloudWatchMetricsService.buildDimKey(dims1),
CloudWatchMetricsService.buildDimKey(dims2));
}
@Test
void buildDimKeyEmptyDimensions() {
assertEquals("", CloudWatchMetricsService.buildDimKey(List.of()));
assertEquals("", CloudWatchMetricsService.buildDimKey(null));
}
}
@@ -0,0 +1,350 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamoDbIntegrationTest {
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
@BeforeAll
static void configureRestAssured() {
RestAssured.config = RestAssured.config().encoderConfig(
EncoderConfig.encoderConfig()
.encodeContentTypeAs(DYNAMODB_CONTENT_TYPE, ContentType.TEXT));
}
@Test
@Order(1)
void createTable() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"KeySchema": [
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"}
],
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"}
],
"ProvisionedThroughput": {
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("TableDescription.TableName", equalTo("TestTable"))
.body("TableDescription.TableStatus", equalTo("ACTIVE"))
.body("TableDescription.KeySchema.size()", equalTo(2));
}
@Test
@Order(2)
void createDuplicateTableFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceInUseException"));
}
@Test
@Order(3)
void describeTable() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName": "TestTable"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Table.TableName", equalTo("TestTable"))
.body("Table.TableArn", containsString("TestTable"));
}
@Test
@Order(4)
void listTables() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("TableNames", hasItem("TestTable"));
}
@Test
@Order(5)
void putItem() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Item": {
"pk": {"S": "user-1"},
"sk": {"S": "profile"},
"name": {"S": "Alice"},
"age": {"N": "30"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(6)
void putMoreItems() {
String[] items = {
"""
{"TableName":"TestTable","Item":{"pk":{"S":"user-1"},"sk":{"S":"order-001"},"total":{"N":"99.99"}}}
""",
"""
{"TableName":"TestTable","Item":{"pk":{"S":"user-1"},"sk":{"S":"order-002"},"total":{"N":"49.50"}}}
""",
"""
{"TableName":"TestTable","Item":{"pk":{"S":"user-2"},"sk":{"S":"profile"},"name":{"S":"Bob"}}}
"""
};
for (String item : items) {
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body(item)
.when()
.post("/")
.then()
.statusCode(200);
}
}
@Test
@Order(7)
void getItem() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Key": {
"pk": {"S": "user-1"},
"sk": {"S": "profile"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Item.name.S", equalTo("Alice"))
.body("Item.age.N", equalTo("30"));
}
@Test
@Order(8)
void getItemNotFound() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Key": {
"pk": {"S": "nonexistent"},
"sk": {"S": "x"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Item", nullValue());
}
@Test
@Order(9)
void query() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"KeyConditionExpression": "pk = :pk",
"ExpressionAttributeValues": {
":pk": {"S": "user-1"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Count", equalTo(3))
.body("Items.size()", equalTo(3));
}
@Test
@Order(10)
void queryWithBeginsWith() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"KeyConditionExpression": "pk = :pk AND begins_with(sk, :prefix)",
"ExpressionAttributeValues": {
":pk": {"S": "user-1"},
":prefix": {"S": "order"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Count", equalTo(2));
}
@Test
@Order(11)
void scan() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.Scan")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName": "TestTable"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Count", equalTo(4))
.body("Items.size()", equalTo(4));
}
@Test
@Order(12)
void deleteItem() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Key": {
"pk": {"S": "user-2"},
"sk": {"S": "profile"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200);
// Verify it's gone
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Key": {
"pk": {"S": "user-2"},
"sk": {"S": "profile"}
}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Item", nullValue());
}
@Test
@Order(13)
void deleteTable() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName": "TestTable"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("TableDescription.TableStatus", equalTo("DELETING"));
// Verify it's gone
given()
.header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName": "TestTable"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void unsupportedOperation() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateGlobalTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("UnknownOperationException"));
}
}
@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class DynamoDbServiceTest {
private DynamoDbService service;
private ObjectMapper mapper;
@BeforeEach
void setUp() {
service = new DynamoDbService(new InMemoryStorage<>());
mapper = new ObjectMapper();
}
private TableDefinition createUsersTable() {
return service.createTable("Users",
List.of(new KeySchemaElement("userId", "HASH")),
List.of(new AttributeDefinition("userId", "S")),
5L, 5L);
}
private TableDefinition createOrdersTable() {
return service.createTable("Orders",
List.of(
new KeySchemaElement("customerId", "HASH"),
new KeySchemaElement("orderId", "RANGE")),
List.of(
new AttributeDefinition("customerId", "S"),
new AttributeDefinition("orderId", "S")),
5L, 5L);
}
private ObjectNode item(String... kvPairs) {
ObjectNode node = mapper.createObjectNode();
for (int i = 0; i < kvPairs.length; i += 2) {
ObjectNode attrValue = mapper.createObjectNode();
attrValue.put("S", kvPairs[i + 1]);
node.set(kvPairs[i], attrValue);
}
return node;
}
@Test
void createTable() {
TableDefinition table = createUsersTable();
assertEquals("Users", table.getTableName());
assertEquals("ACTIVE", table.getTableStatus());
assertNotNull(table.getTableArn());
assertEquals("userId", table.getPartitionKeyName());
assertNull(table.getSortKeyName());
}
@Test
void createTableWithSortKey() {
TableDefinition table = createOrdersTable();
assertEquals("customerId", table.getPartitionKeyName());
assertEquals("orderId", table.getSortKeyName());
}
@Test
void createDuplicateTableThrows() {
createUsersTable();
assertThrows(AwsException.class, () -> createUsersTable());
}
@Test
void describeTable() {
createUsersTable();
TableDefinition table = service.describeTable("Users");
assertEquals("Users", table.getTableName());
}
@Test
void describeTableNotFound() {
assertThrows(AwsException.class, () -> service.describeTable("NonExistent"));
}
@Test
void deleteTable() {
createUsersTable();
service.deleteTable("Users");
assertThrows(AwsException.class, () -> service.describeTable("Users"));
}
@Test
void listTables() {
createUsersTable();
createOrdersTable();
List<String> tables = service.listTables();
assertEquals(2, tables.size());
assertTrue(tables.contains("Users"));
assertTrue(tables.contains("Orders"));
}
@Test
void putAndGetItem() {
createUsersTable();
ObjectNode userItem = item("userId", "user-1", "name", "Alice", "email", "alice@test.com");
service.putItem("Users", userItem);
ObjectNode key = item("userId", "user-1");
JsonNode retrieved = service.getItem("Users", key);
assertNotNull(retrieved);
assertEquals("Alice", retrieved.get("name").get("S").asText());
}
@Test
void getItemNotFound() {
createUsersTable();
ObjectNode key = item("userId", "nonexistent");
JsonNode result = service.getItem("Users", key);
assertNull(result);
}
@Test
void putItemOverwrites() {
createUsersTable();
service.putItem("Users", item("userId", "user-1", "name", "Alice"));
service.putItem("Users", item("userId", "user-1", "name", "Bob"));
JsonNode retrieved = service.getItem("Users", item("userId", "user-1"));
assertEquals("Bob", retrieved.get("name").get("S").asText());
}
@Test
void deleteItem() {
createUsersTable();
service.putItem("Users", item("userId", "user-1", "name", "Alice"));
service.deleteItem("Users", item("userId", "user-1"));
assertNull(service.getItem("Users", item("userId", "user-1")));
}
@Test
void putAndGetWithCompositeKey() {
createOrdersTable();
service.putItem("Orders", item("customerId", "c1", "orderId", "o1", "total", "100"));
service.putItem("Orders", item("customerId", "c1", "orderId", "o2", "total", "200"));
service.putItem("Orders", item("customerId", "c2", "orderId", "o1", "total", "50"));
JsonNode result = service.getItem("Orders", item("customerId", "c1", "orderId", "o1"));
assertNotNull(result);
assertEquals("100", result.get("total").get("S").asText());
}
@Test
void queryByPartitionKey() {
createOrdersTable();
service.putItem("Orders", item("customerId", "c1", "orderId", "o1", "total", "100"));
service.putItem("Orders", item("customerId", "c1", "orderId", "o2", "total", "200"));
service.putItem("Orders", item("customerId", "c2", "orderId", "o1", "total", "50"));
// Build KeyConditions
ObjectNode keyConditions = mapper.createObjectNode();
ObjectNode pkCondition = mapper.createObjectNode();
pkCondition.put("ComparisonOperator", "EQ");
var attrList = mapper.createArrayNode();
ObjectNode pkVal = mapper.createObjectNode();
pkVal.put("S", "c1");
attrList.add(pkVal);
pkCondition.set("AttributeValueList", attrList);
keyConditions.set("customerId", pkCondition);
DynamoDbService.QueryResult results = service.query("Orders", keyConditions, null, null, null, null);
assertEquals(2, results.items().size());
}
@Test
void queryWithKeyConditionExpression() {
createOrdersTable();
service.putItem("Orders", item("customerId", "c1", "orderId", "o1"));
service.putItem("Orders", item("customerId", "c1", "orderId", "o2"));
service.putItem("Orders", item("customerId", "c2", "orderId", "o1"));
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode val = mapper.createObjectNode();
val.put("S", "c1");
exprValues.set(":pk", val);
DynamoDbService.QueryResult results = service.query("Orders", null, exprValues,
"customerId = :pk", null, null);
assertEquals(2, results.items().size());
}
@Test
void queryWithBeginsWith() {
createOrdersTable();
service.putItem("Orders", item("customerId", "c1", "orderId", "2024-01-01"));
service.putItem("Orders", item("customerId", "c1", "orderId", "2024-01-15"));
service.putItem("Orders", item("customerId", "c1", "orderId", "2024-02-01"));
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode pkVal = mapper.createObjectNode();
pkVal.put("S", "c1");
exprValues.set(":pk", pkVal);
ObjectNode skVal = mapper.createObjectNode();
skVal.put("S", "2024-01");
exprValues.set(":sk", skVal);
DynamoDbService.QueryResult results = service.query("Orders", null, exprValues,
"customerId = :pk AND begins_with(orderId, :sk)", null, null);
assertEquals(2, results.items().size());
}
@Test
void scan() {
createUsersTable();
service.putItem("Users", item("userId", "u1", "name", "Alice"));
service.putItem("Users", item("userId", "u2", "name", "Bob"));
service.putItem("Users", item("userId", "u3", "name", "Charlie"));
DynamoDbService.ScanResult result = service.scan("Users", null, null, null, null, null);
assertEquals(3, result.items().size());
}
@Test
void scanWithLimit() {
createUsersTable();
service.putItem("Users", item("userId", "u1"));
service.putItem("Users", item("userId", "u2"));
service.putItem("Users", item("userId", "u3"));
DynamoDbService.ScanResult result = service.scan("Users", null, null, null, 2, null);
assertEquals(2, result.items().size());
}
@Test
void operationsOnNonExistentTableThrow() {
assertThrows(AwsException.class, () -> service.putItem("NoTable", item("id", "1")));
assertThrows(AwsException.class, () -> service.getItem("NoTable", item("id", "1")));
assertThrows(AwsException.class, () -> service.deleteItem("NoTable", item("id", "1")));
assertThrows(AwsException.class, () -> service.query("NoTable", null, null, null, null, null));
assertThrows(AwsException.class, () -> service.scan("NoTable", null, null, null, null, null));
}
}
@@ -0,0 +1,317 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class EventBridgeServiceTest {
private static final String REGION = "us-east-1";
private EventBridgeService service;
@BeforeEach
void setUp() {
service = new EventBridgeService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"),
null, null, null,
new ObjectMapper()
);
}
// ──────────────────────────── Event Buses ────────────────────────────
@Test
void getOrCreateDefaultBus() {
EventBus bus = service.getOrCreateDefaultBus(REGION);
assertEquals("default", bus.getName());
assertNotNull(bus.getArn());
}
@Test
void createEventBus() {
EventBus bus = service.createEventBus("my-bus", "A custom bus", null, REGION);
assertEquals("my-bus", bus.getName());
assertTrue(bus.getArn().contains("my-bus"));
}
@Test
void createEventBusDuplicateThrows() {
service.createEventBus("my-bus", null, null, REGION);
assertThrows(AwsException.class, () ->
service.createEventBus("my-bus", null, null, REGION));
}
@Test
void createEventBusBlankNameThrows() {
assertThrows(AwsException.class, () ->
service.createEventBus("", null, null, REGION));
}
@Test
void deleteEventBus() {
service.createEventBus("my-bus", null, null, REGION);
service.deleteEventBus("my-bus", REGION);
assertThrows(AwsException.class, () ->
service.describeEventBus("my-bus", REGION));
}
@Test
void deleteDefaultBusThrows() {
assertThrows(AwsException.class, () ->
service.deleteEventBus("default", REGION));
}
@Test
void deleteEventBusWithRulesThrows() {
service.createEventBus("my-bus", null, null, REGION);
service.putRule("rule-1", "my-bus", null, "rate(1 minute)", RuleState.ENABLED, null, null, null, REGION);
assertThrows(AwsException.class, () ->
service.deleteEventBus("my-bus", REGION));
}
@Test
void listEventBuses() {
service.createEventBus("bus-a", null, null, REGION);
service.createEventBus("bus-b", null, null, REGION);
List<EventBus> buses = service.listEventBuses(null, REGION);
// default + bus-a + bus-b
assertEquals(3, buses.size());
}
@Test
void listEventBusesWithPrefix() {
service.createEventBus("prod-orders", null, null, REGION);
service.createEventBus("prod-payments", null, null, REGION);
service.createEventBus("dev-orders", null, null, REGION);
List<EventBus> result = service.listEventBuses("prod-", REGION);
assertEquals(2, result.size());
}
// ──────────────────────────── Rules ────────────────────────────
@Test
void putRule() {
Rule rule = service.putRule("my-rule", null,
"{\"source\":[\"my.app\"]}", null, RuleState.ENABLED,
"A test rule", null, null, REGION);
assertEquals("my-rule", rule.getName());
assertEquals(RuleState.ENABLED, rule.getState());
assertNotNull(rule.getArn());
}
@Test
void putRuleIsIdempotent() {
service.putRule("my-rule", null, null, "rate(5 minutes)", RuleState.ENABLED,
null, null, null, REGION);
service.putRule("my-rule", null, null, "rate(10 minutes)", RuleState.ENABLED,
null, null, null, REGION);
List<Rule> rules = service.listRules(null, null, REGION);
assertEquals(1, rules.size());
assertEquals("rate(10 minutes)", rules.getFirst().getScheduleExpression());
}
@Test
void putRuleForNonExistentBusThrows() {
assertThrows(AwsException.class, () ->
service.putRule("rule", "missing-bus", null, null, null, null, null, null, REGION));
}
@Test
void deleteRule() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
service.deleteRule("my-rule", null, REGION);
assertTrue(service.listRules(null, null, REGION).isEmpty());
}
@Test
void deleteRuleWithTargetsThrows() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
Target target = new Target();
target.setId("t1");
target.setArn("arn:aws:sqs:us-east-1:000000000000:my-queue");
service.putTargets("my-rule", null, List.of(target), REGION);
assertThrows(AwsException.class, () ->
service.deleteRule("my-rule", null, REGION));
}
@Test
void enableAndDisableRule() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.DISABLED,
null, null, null, REGION);
service.enableRule("my-rule", null, REGION);
assertEquals(RuleState.ENABLED, service.describeRule("my-rule", null, REGION).getState());
service.disableRule("my-rule", null, REGION);
assertEquals(RuleState.DISABLED, service.describeRule("my-rule", null, REGION).getState());
}
@Test
void listRulesWithPrefix() {
service.putRule("prod-rule-1", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
service.putRule("prod-rule-2", null, null, "rate(5 minutes)", RuleState.ENABLED,
null, null, null, REGION);
service.putRule("dev-rule-1", null, null, "rate(1 hour)", RuleState.ENABLED,
null, null, null, REGION);
List<Rule> result = service.listRules(null, "prod-", REGION);
assertEquals(2, result.size());
}
// ──────────────────────────── Targets ────────────────────────────
@Test
void putAndListTargets() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
Target t1 = new Target();
t1.setId("target-1");
t1.setArn("arn:aws:sqs:us-east-1:000000000000:queue-1");
Target t2 = new Target();
t2.setId("target-2");
t2.setArn("arn:aws:sqs:us-east-1:000000000000:queue-2");
service.putTargets("my-rule", null, List.of(t1, t2), REGION);
List<Target> targets = service.listTargetsByRule("my-rule", null, REGION);
assertEquals(2, targets.size());
}
@Test
void putTargetsIsIdempotent() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
Target t = new Target();
t.setId("t1");
t.setArn("arn:aws:sqs:us-east-1:000000000000:queue");
service.putTargets("my-rule", null, List.of(t), REGION);
t.setArn("arn:aws:sqs:us-east-1:000000000000:queue-updated");
service.putTargets("my-rule", null, List.of(t), REGION);
List<Target> targets = service.listTargetsByRule("my-rule", null, REGION);
assertEquals(1, targets.size());
assertEquals("arn:aws:sqs:us-east-1:000000000000:queue-updated", targets.getFirst().getArn());
}
@Test
void removeTargets() {
service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED,
null, null, null, REGION);
Target t1 = new Target();
t1.setId("t1");
t1.setArn("arn:aws:sqs:us-east-1:000000000000:queue-1");
Target t2 = new Target();
t2.setId("t2");
t2.setArn("arn:aws:sqs:us-east-1:000000000000:queue-2");
service.putTargets("my-rule", null, List.of(t1, t2), REGION);
EventBridgeService.RemoveTargetsResult result = service.removeTargets(
"my-rule", null, List.of("t1"), REGION);
assertEquals(1, result.successfulCount());
assertEquals(0, result.failedCount());
assertEquals(1, service.listTargetsByRule("my-rule", null, REGION).size());
}
// ──────────────────────────── Pattern Matching ────────────────────────────
@Test
void matchesPatternNullPatternAlwaysMatches() {
Map<String, Object> event = Map.of("Source", "my.app", "DetailType", "Order");
assertTrue(service.matchesPattern(event, null));
assertTrue(service.matchesPattern(event, ""));
}
@Test
void matchesPatternBySource() {
Map<String, Object> event = Map.of("Source", "my.app", "DetailType", "Order");
assertTrue(service.matchesPattern(event, "{\"source\":[\"my.app\"]}"));
assertFalse(service.matchesPattern(event, "{\"source\":[\"other.app\"]}"));
}
@Test
void matchesPatternByDetailType() {
Map<String, Object> event = Map.of("Source", "my.app", "DetailType", "OrderCreated");
assertTrue(service.matchesPattern(event, "{\"detail-type\":[\"OrderCreated\"]}"));
assertFalse(service.matchesPattern(event, "{\"detail-type\":[\"OrderDeleted\"]}"));
}
@Test
void matchesPatternBySourceAndDetailType() {
Map<String, Object> event = Map.of("Source", "my.app", "DetailType", "OrderCreated");
assertTrue(service.matchesPattern(event,
"{\"source\":[\"my.app\"],\"detail-type\":[\"OrderCreated\"]}"));
assertFalse(service.matchesPattern(event,
"{\"source\":[\"my.app\"],\"detail-type\":[\"OrderDeleted\"]}"));
}
@Test
void matchesPatternByDetail() {
Map<String, Object> event = Map.of(
"Source", "my.app",
"Detail", "{\"status\":\"CONFIRMED\",\"amount\":\"100\"}"
);
assertTrue(service.matchesPattern(event, "{\"detail\":{\"status\":[\"CONFIRMED\"]}}"));
assertFalse(service.matchesPattern(event, "{\"detail\":{\"status\":[\"PENDING\"]}}"));
}
@Test
void putEventsReturnsEventIds() {
List<Map<String, Object>> entries = List.of(
Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")
);
EventBridgeService.PutEventsResult result = service.putEvents(entries, REGION);
assertEquals(0, result.failedCount());
assertEquals(1, result.entries().size());
assertNotNull(result.entries().getFirst().get("EventId"));
}
@Test
void putEventsFailsForNonExistentBus() {
List<Map<String, Object>> entries = List.of(
Map.of("Source", "my.app", "DetailType", "Test",
"Detail", "{}", "EventBusName", "non-existent-bus")
);
EventBridgeService.PutEventsResult result = service.putEvents(entries, REGION);
assertEquals(1, result.failedCount());
}
}
@@ -0,0 +1,498 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for IAM and STS via the Query Protocol (form-encoded POST, XML response).
* Covers the full HTTP stack through {@link AwsQueryController}
* → {@link IamQueryHandler} and {@link StsQueryHandler}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class IamIntegrationTest {
private static final String TRUST_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
private static final String POLICY_DOCUMENT =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
private static String createdPolicyArn;
// =========================================================================
// STS
// =========================================================================
@Test
@Order(1)
void stsGetCallerIdentity() {
given()
.formParam("Action", "GetCallerIdentity")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/sts/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo("000000000000"))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
containsString("arn:aws:iam::000000000000:root"));
}
@Test
@Order(2)
void stsAssumeRole() {
given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::000000000000:role/TestRole")
.formParam("RoleSessionName", "test-session")
.formParam("DurationSeconds", "3600")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/sts/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId",
startsWith("ASIA"))
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.SecretAccessKey", notNullValue())
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken", notNullValue())
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.Expiration", notNullValue())
.body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",
containsString("assumed-role/TestRole/test-session"));
}
// =========================================================================
// Users
// =========================================================================
@Test
@Order(10)
void createUser() {
given()
.formParam("Action", "CreateUser")
.formParam("UserName", "test-user")
.formParam("Path", "/")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("CreateUserResponse.CreateUserResult.User.UserName", equalTo("test-user"))
.body("CreateUserResponse.CreateUserResult.User.Path", equalTo("/"))
.body("CreateUserResponse.CreateUserResult.User.UserId", startsWith("AIDA"))
.body("CreateUserResponse.CreateUserResult.User.Arn",
equalTo("arn:aws:iam::000000000000:user/test-user"));
}
@Test
@Order(11)
void createUserDuplicateReturns409() {
given()
.formParam("Action", "CreateUser")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(409);
}
@Test
@Order(12)
void getUser() {
given()
.formParam("Action", "GetUser")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetUserResponse.GetUserResult.User.UserName", equalTo("test-user"));
}
@Test
@Order(13)
void listUsers() {
given()
.formParam("Action", "ListUsers")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListUsersResponse.ListUsersResult.Users.member.UserName",
equalTo("test-user"));
}
@Test
@Order(14)
void tagAndListUserTags() {
given()
.formParam("Action", "TagUser")
.formParam("UserName", "test-user")
.formParam("Tags.member.1.Key", "env")
.formParam("Tags.member.1.Value", "test")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "ListUserTags")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListUserTagsResponse.ListUserTagsResult.Tags.member.Key", equalTo("env"));
}
// =========================================================================
// Roles
// =========================================================================
@Test
@Order(20)
void createRole() {
given()
.formParam("Action", "CreateRole")
.formParam("RoleName", "TestRole")
.formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.formParam("Description", "Integration test role")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateRoleResponse.CreateRoleResult.Role.RoleName", equalTo("TestRole"))
.body("CreateRoleResponse.CreateRoleResult.Role.RoleId", startsWith("AROA"))
.body("CreateRoleResponse.CreateRoleResult.Role.Arn",
equalTo("arn:aws:iam::000000000000:role/TestRole"))
.body("CreateRoleResponse.CreateRoleResult.Role.Description", equalTo("Integration test role"));
}
@Test
@Order(21)
void getRole() {
given()
.formParam("Action", "GetRole")
.formParam("RoleName", "TestRole")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetRoleResponse.GetRoleResult.Role.RoleName", equalTo("TestRole"));
}
@Test
@Order(22)
void listRoles() {
given()
.formParam("Action", "ListRoles")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListRolesResponse.ListRolesResult.Roles.member.RoleName",
equalTo("TestRole"));
}
// =========================================================================
// Managed Policies
// =========================================================================
@Test
@Order(30)
void createPolicy() {
createdPolicyArn = given()
.formParam("Action", "CreatePolicy")
.formParam("PolicyName", "TestPolicy")
.formParam("Path", "/")
.formParam("PolicyDocument", POLICY_DOCUMENT)
.formParam("Description", "Test managed policy")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreatePolicyResponse.CreatePolicyResult.Policy.PolicyName", equalTo("TestPolicy"))
.body("CreatePolicyResponse.CreatePolicyResult.Policy.PolicyId", startsWith("ANPA"))
.body("CreatePolicyResponse.CreatePolicyResult.Policy.DefaultVersionId", equalTo("v1"))
.extract()
.path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
}
@Test
@Order(31)
void getPolicy() {
given()
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", createdPolicyArn)
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetPolicyResponse.GetPolicyResult.Policy.PolicyName", equalTo("TestPolicy"));
}
@Test
@Order(32)
void attachRolePolicyAndList() {
given()
.formParam("Action", "AttachRolePolicy")
.formParam("RoleName", "TestRole")
.formParam("PolicyArn", createdPolicyArn)
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "ListAttachedRolePolicies")
.formParam("RoleName", "TestRole")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListAttachedRolePoliciesResponse.ListAttachedRolePoliciesResult.AttachedPolicies.member.PolicyName",
equalTo("TestPolicy"));
}
@Test
@Order(33)
void putAndGetRoleInlinePolicy() {
given()
.formParam("Action", "PutRolePolicy")
.formParam("RoleName", "TestRole")
.formParam("PolicyName", "inline-logging")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\"}")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", "TestRole")
.formParam("PolicyName", "inline-logging")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetRolePolicyResponse.GetRolePolicyResult.PolicyName", equalTo("inline-logging"));
}
// =========================================================================
// Access Keys
// =========================================================================
@Test
@Order(40)
void createAndListAccessKeys() {
given()
.formParam("Action", "CreateAccessKey")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId",
startsWith("AKIA"))
.body("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey",
notNullValue())
.body("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.Status",
equalTo("Active"));
given()
.formParam("Action", "ListAccessKeys")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.UserName",
equalTo("test-user"));
}
// =========================================================================
// Groups
// =========================================================================
@Test
@Order(50)
void createGroupAndAddUser() {
given()
.formParam("Action", "CreateGroup")
.formParam("GroupName", "test-group")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateGroupResponse.CreateGroupResult.Group.GroupName", equalTo("test-group"))
.body("CreateGroupResponse.CreateGroupResult.Group.GroupId", startsWith("AGPA"));
given()
.formParam("Action", "AddUserToGroup")
.formParam("GroupName", "test-group")
.formParam("UserName", "test-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "GetGroup")
.formParam("GroupName", "test-group")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetGroupResponse.GetGroupResult.Group.GroupName", equalTo("test-group"))
.body("GetGroupResponse.GetGroupResult.Users.member.UserName",
equalTo("test-user"));
}
// =========================================================================
// Instance Profiles
// =========================================================================
@Test
@Order(60)
void createInstanceProfileAndAddRole() {
// Detach policy from role first so we can test cleanly
given()
.formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", "test-profile")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.InstanceProfileName",
equalTo("test-profile"))
.body("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.InstanceProfileId",
startsWith("AIPA"));
given()
.formParam("Action", "AddRoleToInstanceProfile")
.formParam("InstanceProfileName", "test-profile")
.formParam("RoleName", "TestRole")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "GetInstanceProfile")
.formParam("InstanceProfileName", "test-profile")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("GetInstanceProfileResponse.GetInstanceProfileResult.InstanceProfile.InstanceProfileName",
equalTo("test-profile"))
.body("GetInstanceProfileResponse.GetInstanceProfileResult.InstanceProfile.Roles.member.RoleName",
equalTo("TestRole"));
}
// =========================================================================
// Error cases
// =========================================================================
@Test
@Order(70)
void getUserNotFoundReturns404() {
given()
.formParam("Action", "GetUser")
.formParam("UserName", "nonexistent-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
@Order(71)
void getRoleNotFoundReturns404() {
given()
.formParam("Action", "GetRole")
.formParam("RoleName", "nonexistent-role")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(404);
}
@Test
@Order(72)
void unsupportedIamActionReturns400() {
given()
.formParam("Action", "UnknownIamAction")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("UnsupportedOperation"));
}
}
@@ -0,0 +1,448 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class IamServiceTest {
private IamService iamService;
@BeforeEach
void setUp() {
iamService = new IamService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"000000000000"
);
}
// =========================================================================
// Users
// =========================================================================
@Test
void createAndGetUser() {
IamUser user = iamService.createUser("alice", "/");
assertEquals("alice", user.getUserName());
assertEquals("/", user.getPath());
assertNotNull(user.getUserId());
assertTrue(user.getUserId().startsWith("AIDA"));
assertEquals("arn:aws:iam::000000000000:user/alice", user.getArn());
assertNotNull(user.getCreateDate());
}
@Test
void createUserDuplicateFails() {
iamService.createUser("alice", "/");
assertThrows(AwsException.class, () -> iamService.createUser("alice", "/"));
}
@Test
void getUserNotFoundThrows() {
assertThrows(AwsException.class, () -> iamService.getUser("nonexistent"));
}
@Test
void deleteUser() {
iamService.createUser("alice", "/");
iamService.deleteUser("alice");
assertThrows(AwsException.class, () -> iamService.getUser("alice"));
}
@Test
void deleteUserWithAttachedPolicyFails() {
iamService.createUser("alice", "/");
String policyArn = iamService.createPolicy("MyPolicy", "/", null,
"{\"Version\":\"2012-10-17\"}", null).getArn();
iamService.attachUserPolicy("alice", policyArn);
assertThrows(AwsException.class, () -> iamService.deleteUser("alice"));
}
@Test
void listUsers() {
iamService.createUser("alice", "/");
iamService.createUser("bob", "/team/");
iamService.createUser("carol", "/admin/");
List<IamUser> all = iamService.listUsers("/");
assertEquals(3, all.size());
List<IamUser> teamOnly = iamService.listUsers("/team/");
assertEquals(1, teamOnly.size());
assertEquals("bob", teamOnly.getFirst().getUserName());
}
@Test
void updateUser() {
iamService.createUser("alice", "/");
iamService.updateUser("alice", "alice-renamed", "/new/");
assertThrows(AwsException.class, () -> iamService.getUser("alice"));
IamUser renamed = iamService.getUser("alice-renamed");
assertEquals("/new/", renamed.getPath());
}
@Test
void tagAndUntagUser() {
iamService.createUser("alice", "/");
iamService.tagUser("alice", Map.of("env", "prod", "team", "eng"));
Map<String, String> tags = iamService.listUserTags("alice");
assertEquals("prod", tags.get("env"));
assertEquals("eng", tags.get("team"));
iamService.untagUser("alice", List.of("team"));
Map<String, String> tags2 = iamService.listUserTags("alice");
assertFalse(tags2.containsKey("team"));
assertTrue(tags2.containsKey("env"));
}
// =========================================================================
// Groups
// =========================================================================
@Test
void createAndGetGroup() {
IamGroup group = iamService.createGroup("developers", "/");
assertEquals("developers", group.getGroupName());
assertEquals("/", group.getPath());
assertTrue(group.getGroupId().startsWith("AGPA"));
assertEquals("arn:aws:iam::000000000000:group/developers", group.getArn());
}
@Test
void addAndRemoveUserFromGroup() {
iamService.createUser("alice", "/");
iamService.createGroup("developers", "/");
iamService.addUserToGroup("developers", "alice");
IamGroup group = iamService.getGroup("developers");
assertTrue(group.getUserNames().contains("alice"));
IamUser user = iamService.getUser("alice");
assertTrue(user.getGroupNames().contains("developers"));
iamService.removeUserFromGroup("developers", "alice");
assertFalse(iamService.getGroup("developers").getUserNames().contains("alice"));
assertFalse(iamService.getUser("alice").getGroupNames().contains("developers"));
}
@Test
void listGroupsForUser() {
iamService.createUser("alice", "/");
iamService.createGroup("dev", "/");
iamService.createGroup("ops", "/");
iamService.addUserToGroup("dev", "alice");
iamService.addUserToGroup("ops", "alice");
List<IamGroup> groups = iamService.listGroupsForUser("alice");
assertEquals(2, groups.size());
}
@Test
void deleteGroupWithUsersFails() {
iamService.createUser("alice", "/");
iamService.createGroup("dev", "/");
iamService.addUserToGroup("dev", "alice");
assertThrows(AwsException.class, () -> iamService.deleteGroup("dev"));
}
// =========================================================================
// Roles
// =========================================================================
@Test
void createAndGetRole() {
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
IamRole role = iamService.createRole("LambdaExec", "/", trustPolicy, "Lambda role", 3600, null);
assertEquals("LambdaExec", role.getRoleName());
assertEquals("/", role.getPath());
assertTrue(role.getRoleId().startsWith("AROA"));
assertEquals("arn:aws:iam::000000000000:role/LambdaExec", role.getArn());
assertEquals(trustPolicy, role.getAssumeRolePolicyDocument());
assertEquals("Lambda role", role.getDescription());
}
@Test
void deleteRoleWithAttachedPolicyFails() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
String policyArn = iamService.createPolicy("P", "/", null, "{}", null).getArn();
iamService.attachRolePolicy("LambdaExec", policyArn);
assertThrows(AwsException.class, () -> iamService.deleteRole("LambdaExec"));
}
@Test
void tagAndUntagRole() {
iamService.createRole("MyRole", "/", "{}", null, 0, Map.of("env", "test"));
iamService.tagRole("MyRole", Map.of("owner", "team-a"));
Map<String, String> tags = iamService.listRoleTags("MyRole");
assertEquals("test", tags.get("env"));
assertEquals("team-a", tags.get("owner"));
iamService.untagRole("MyRole", List.of("env"));
assertFalse(iamService.listRoleTags("MyRole").containsKey("env"));
}
// =========================================================================
// Managed Policies
// =========================================================================
@Test
void createAndGetPolicy() {
String doc = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
IamPolicy policy = iamService.createPolicy("ReadOnly", "/", "Read-only access", doc, null);
assertEquals("ReadOnly", policy.getPolicyName());
assertEquals("/", policy.getPath());
assertTrue(policy.getPolicyId().startsWith("ANPA"));
assertEquals("arn:aws:iam::000000000000:policy/ReadOnly", policy.getArn());
assertEquals("v1", policy.getDefaultVersionId());
assertEquals(doc, policy.getDefaultDocument());
}
@Test
void createPolicyVersionAndSetDefault() {
String doc1 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
String doc2 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\"}]}";
IamPolicy policy = iamService.createPolicy("P", "/", null, doc1, null);
String policyArn = policy.getArn();
PolicyVersion v2 = iamService.createPolicyVersion(policyArn, doc2, false);
assertEquals("v2", v2.getVersionId());
assertFalse(v2.isDefaultVersion());
iamService.setDefaultPolicyVersion(policyArn, "v2");
IamPolicy updated = iamService.getPolicy(policyArn);
assertEquals("v2", updated.getDefaultVersionId());
assertEquals(doc2, updated.getDefaultDocument());
}
@Test
void deletePolicyVersionDefaultFails() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
assertThrows(AwsException.class,
() -> iamService.deletePolicyVersion(policy.getArn(), "v1"));
}
@Test
void policyVersionLimit() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", false);
}
assertThrows(AwsException.class,
() -> iamService.createPolicyVersion(arn, "{\"v\":6}", false));
}
@Test
void deletePolicyWithAttachmentsFails() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.attachUserPolicy("alice", policy.getArn());
assertThrows(AwsException.class, () -> iamService.deletePolicy(policy.getArn()));
}
@Test
void tagAndUntagPolicy() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.tagPolicy(policy.getArn(), Map.of("team", "security"));
assertEquals("security", iamService.listPolicyTags(policy.getArn()).get("team"));
iamService.untagPolicy(policy.getArn(), List.of("team"));
assertFalse(iamService.listPolicyTags(policy.getArn()).containsKey("team"));
}
// =========================================================================
// Policy Attachments
// =========================================================================
@Test
void attachAndDetachUserPolicy() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.attachUserPolicy("alice", policy.getArn());
List<IamPolicy> attached = iamService.listAttachedUserPolicies("alice", null);
assertEquals(1, attached.size());
assertEquals(policy.getArn(), attached.getFirst().getArn());
assertEquals(1, iamService.getPolicy(policy.getArn()).getAttachmentCount());
iamService.detachUserPolicy("alice", policy.getArn());
assertTrue(iamService.listAttachedUserPolicies("alice", null).isEmpty());
assertEquals(0, iamService.getPolicy(policy.getArn()).getAttachmentCount());
}
@Test
void attachAndDetachGroupPolicy() {
iamService.createGroup("dev", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.attachGroupPolicy("dev", policy.getArn());
assertEquals(1, iamService.listAttachedGroupPolicies("dev", null).size());
iamService.detachGroupPolicy("dev", policy.getArn());
assertTrue(iamService.listAttachedGroupPolicies("dev", null).isEmpty());
}
@Test
void attachAndDetachRolePolicy() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.attachRolePolicy("LambdaExec", policy.getArn());
assertEquals(1, iamService.listAttachedRolePolicies("LambdaExec", null).size());
iamService.detachRolePolicy("LambdaExec", policy.getArn());
assertTrue(iamService.listAttachedRolePolicies("LambdaExec", null).isEmpty());
}
@Test
void detachNonAttachedPolicyThrows() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
assertThrows(AwsException.class, () -> iamService.detachUserPolicy("alice", policy.getArn()));
}
// =========================================================================
// Inline Policies
// =========================================================================
@Test
void userInlinePolicyCrud() {
iamService.createUser("alice", "/");
String doc = "{\"Version\":\"2012-10-17\"}";
iamService.putUserPolicy("alice", "inline-1", doc);
assertEquals(doc, iamService.getUserPolicy("alice", "inline-1"));
assertEquals(List.of("inline-1"), iamService.listUserPolicies("alice"));
iamService.deleteUserPolicy("alice", "inline-1");
assertTrue(iamService.listUserPolicies("alice").isEmpty());
}
@Test
void roleInlinePolicyCrud() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.putRolePolicy("R", "inline-exec", "{\"Effect\":\"Allow\"}");
assertEquals("{\"Effect\":\"Allow\"}", iamService.getRolePolicy("R", "inline-exec"));
iamService.deleteRolePolicy("R", "inline-exec");
assertThrows(AwsException.class, () -> iamService.getRolePolicy("R", "inline-exec"));
}
// =========================================================================
// Access Keys
// =========================================================================
@Test
void createAndListAccessKeys() {
iamService.createUser("alice", "/");
AccessKey key = iamService.createAccessKey("alice");
assertNotNull(key.getAccessKeyId());
assertTrue(key.getAccessKeyId().startsWith("AKIA"));
assertNotNull(key.getSecretAccessKey());
assertEquals("alice", key.getUserName());
assertEquals("Active", key.getStatus());
List<AccessKey> keys = iamService.listAccessKeys("alice");
assertEquals(1, keys.size());
}
@Test
void createThirdAccessKeyFails() {
iamService.createUser("alice", "/");
iamService.createAccessKey("alice");
iamService.createAccessKey("alice");
assertThrows(AwsException.class, () -> iamService.createAccessKey("alice"));
}
@Test
void deleteAndUpdateAccessKey() {
iamService.createUser("alice", "/");
AccessKey key = iamService.createAccessKey("alice");
iamService.updateAccessKey("alice", key.getAccessKeyId(), "Inactive");
AccessKey updated = iamService.listAccessKeys("alice").getFirst();
assertEquals("Inactive", updated.getStatus());
iamService.deleteAccessKey("alice", key.getAccessKeyId());
assertTrue(iamService.listAccessKeys("alice").isEmpty());
}
// =========================================================================
// Instance Profiles
// =========================================================================
@Test
void createAndGetInstanceProfile() {
InstanceProfile profile = iamService.createInstanceProfile("MyProfile", "/");
assertEquals("MyProfile", profile.getInstanceProfileName());
assertTrue(profile.getInstanceProfileId().startsWith("AIPA"));
assertEquals("arn:aws:iam::000000000000:instance-profile/MyProfile", profile.getArn());
}
@Test
void addAndRemoveRoleFromInstanceProfile() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
iamService.createInstanceProfile("MyProfile", "/");
iamService.addRoleToInstanceProfile("MyProfile", "LambdaExec");
InstanceProfile profile = iamService.getInstanceProfile("MyProfile");
assertTrue(profile.getRoleNames().contains("LambdaExec"));
iamService.removeRoleFromInstanceProfile("MyProfile", "LambdaExec");
assertFalse(iamService.getInstanceProfile("MyProfile").getRoleNames().contains("LambdaExec"));
}
@Test
void instanceProfileMaxOneRole() {
iamService.createRole("Role1", "/", "{}", null, 0, null);
iamService.createRole("Role2", "/", "{}", null, 0, null);
iamService.createInstanceProfile("Profile", "/");
iamService.addRoleToInstanceProfile("Profile", "Role1");
assertThrows(AwsException.class,
() -> iamService.addRoleToInstanceProfile("Profile", "Role2"));
}
@Test
void deleteInstanceProfileWithRoleFails() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createInstanceProfile("P", "/");
iamService.addRoleToInstanceProfile("P", "R");
assertThrows(AwsException.class, () -> iamService.deleteInstanceProfile("P"));
}
@Test
void listInstanceProfilesForRole() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createInstanceProfile("P1", "/");
iamService.createInstanceProfile("P2", "/");
iamService.addRoleToInstanceProfile("P1", "R");
List<InstanceProfile> profiles = iamService.listInstanceProfilesForRole("R");
assertEquals(1, profiles.size());
assertEquals("P1", profiles.getFirst().getInstanceProfileName());
}
}
@@ -0,0 +1,209 @@
package io.github.hectorvent.floci.services.kinesis;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.kinesis.model.KinesisConsumer;
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class KinesisServiceTest {
private static final String REGION = "us-east-1";
private KinesisService kinesisService;
@BeforeEach
void setUp() {
kinesisService = new KinesisService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000")
);
}
@Test
void createStream() {
KinesisStream stream = kinesisService.createStream("my-stream", 2, REGION);
assertEquals("my-stream", stream.getStreamName());
assertNotNull(stream.getStreamArn());
assertEquals(2, stream.getShards().size());
assertEquals("ACTIVE", stream.getStreamStatus());
}
@Test
void createStreamAlreadyExistsThrows() {
kinesisService.createStream("my-stream", 1, REGION);
assertThrows(AwsException.class, () ->
kinesisService.createStream("my-stream", 1, REGION));
}
@Test
void listStreams() {
kinesisService.createStream("stream-a", 1, REGION);
kinesisService.createStream("stream-b", 1, REGION);
kinesisService.createStream("other", 1, "eu-west-1");
List<String> names = kinesisService.listStreams(REGION);
assertEquals(2, names.size());
assertTrue(names.containsAll(List.of("stream-a", "stream-b")));
}
@Test
void describeStreamNotFound() {
assertThrows(AwsException.class, () ->
kinesisService.describeStream("missing", REGION));
}
@Test
void deleteStream() {
kinesisService.createStream("to-delete", 1, REGION);
kinesisService.deleteStream("to-delete", REGION);
assertTrue(kinesisService.listStreams(REGION).isEmpty());
}
@Test
void putAndGetRecord() {
kinesisService.createStream("my-stream", 1, REGION);
String seqNum = kinesisService.putRecord("my-stream",
"hello".getBytes(StandardCharsets.UTF_8), "partition-1", REGION);
assertNotNull(seqNum);
KinesisStream stream = kinesisService.describeStream("my-stream", REGION);
String shardId = stream.getShards().getFirst().getShardId();
String iterator = kinesisService.getShardIterator("my-stream", shardId,
"TRIM_HORIZON", null, REGION);
Map<String, Object> result = kinesisService.getRecords(iterator, 10, REGION);
@SuppressWarnings("unchecked")
var records = (List<?>) result.get("Records");
assertEquals(1, records.size());
}
@Test
void getRecordsLatestIteratorReturnsEmpty() {
kinesisService.createStream("my-stream", 1, REGION);
kinesisService.putRecord("my-stream", "msg".getBytes(StandardCharsets.UTF_8), "pk", REGION);
String shardId = kinesisService.describeStream("my-stream", REGION).getShards().getFirst().getShardId();
String iterator = kinesisService.getShardIterator("my-stream", shardId, "LATEST", null, REGION);
Map<String, Object> result = kinesisService.getRecords(iterator, 10, REGION);
@SuppressWarnings("unchecked")
var records = (List<?>) result.get("Records");
assertTrue(records.isEmpty());
}
@Test
void addAndListTags() {
kinesisService.createStream("tagged", 1, REGION);
kinesisService.addTagsToStream("tagged", Map.of("env", "prod", "team", "infra"), REGION);
Map<String, String> tags = kinesisService.listTagsForStream("tagged", REGION);
assertEquals("prod", tags.get("env"));
assertEquals("infra", tags.get("team"));
}
@Test
void removeTags() {
kinesisService.createStream("tagged", 1, REGION);
kinesisService.addTagsToStream("tagged", Map.of("env", "prod", "team", "infra"), REGION);
kinesisService.removeTagsFromStream("tagged", List.of("env"), REGION);
Map<String, String> tags = kinesisService.listTagsForStream("tagged", REGION);
assertFalse(tags.containsKey("env"));
assertTrue(tags.containsKey("team"));
}
@Test
void registerAndDescribeConsumer() {
KinesisStream stream = kinesisService.createStream("my-stream", 1, REGION);
KinesisConsumer consumer = kinesisService.registerStreamConsumer(
stream.getStreamArn(), "my-consumer", REGION);
assertNotNull(consumer.getConsumerArn());
assertEquals("my-consumer", consumer.getConsumerName());
KinesisConsumer described = kinesisService.describeStreamConsumer(
stream.getStreamArn(), "my-consumer", null, REGION);
assertEquals(consumer.getConsumerArn(), described.getConsumerArn());
}
@Test
void listStreamConsumers() {
KinesisStream stream = kinesisService.createStream("my-stream", 1, REGION);
kinesisService.registerStreamConsumer(stream.getStreamArn(), "c1", REGION);
kinesisService.registerStreamConsumer(stream.getStreamArn(), "c2", REGION);
List<KinesisConsumer> consumers = kinesisService.listStreamConsumers(stream.getStreamArn(), REGION);
assertEquals(2, consumers.size());
}
@Test
void deregisterConsumer() {
KinesisStream stream = kinesisService.createStream("my-stream", 1, REGION);
KinesisConsumer consumer = kinesisService.registerStreamConsumer(
stream.getStreamArn(), "my-consumer", REGION);
kinesisService.deregisterStreamConsumer(
stream.getStreamArn(), "my-consumer", consumer.getConsumerArn(), REGION);
assertTrue(kinesisService.listStreamConsumers(stream.getStreamArn(), REGION).isEmpty());
}
@Test
void splitShard() {
kinesisService.createStream("my-stream", 1, REGION);
KinesisStream stream = kinesisService.describeStream("my-stream", REGION);
String shardId = stream.getShards().getFirst().getShardId();
kinesisService.splitShard("my-stream", shardId, "170141183460469231731687303715884105728", REGION);
KinesisStream updated = kinesisService.describeStream("my-stream", REGION);
assertEquals(3, updated.getShards().size());
assertTrue(updated.getShards().getFirst().isClosed());
}
@Test
void mergeShards() {
kinesisService.createStream("my-stream", 2, REGION);
KinesisStream stream = kinesisService.describeStream("my-stream", REGION);
String shard0 = stream.getShards().get(0).getShardId();
String shard1 = stream.getShards().get(1).getShardId();
kinesisService.mergeShards("my-stream", shard0, shard1, REGION);
KinesisStream updated = kinesisService.describeStream("my-stream", REGION);
assertEquals(3, updated.getShards().size());
assertTrue(updated.getShards().get(0).isClosed());
assertTrue(updated.getShards().get(1).isClosed());
assertFalse(updated.getShards().get(2).isClosed());
}
@Test
void startAndStopEncryption() {
kinesisService.createStream("my-stream", 1, REGION);
kinesisService.startStreamEncryption("my-stream", "KMS", "my-key-id", REGION);
KinesisStream encrypted = kinesisService.describeStream("my-stream", REGION);
assertEquals("KMS", encrypted.getEncryptionType());
assertEquals("my-key-id", encrypted.getKeyId());
kinesisService.stopStreamEncryption("my-stream", REGION);
KinesisStream unencrypted = kinesisService.describeStream("my-stream", REGION);
assertEquals("NONE", unencrypted.getEncryptionType());
assertNull(unencrypted.getKeyId());
}
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.kms;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class KmsServiceTest {
private static final String REGION = "us-east-1";
private KmsService kmsService;
@BeforeEach
void setUp() {
kmsService = new KmsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000")
);
}
@Test
void createKeyAndDescribe() {
KmsKey key = kmsService.createKey("my test key", REGION);
assertNotNull(key.getKeyId());
assertNotNull(key.getArn());
assertTrue(key.getArn().contains("key/"));
assertEquals("my test key", key.getDescription());
assertEquals("Enabled", key.getKeyState());
}
@Test
void listKeys() {
kmsService.createKey("key1", REGION);
kmsService.createKey("key2", REGION);
kmsService.createKey("key3", "eu-west-1");
List<KmsKey> keys = kmsService.listKeys(REGION);
assertEquals(2, keys.size());
}
@Test
void describeKeyNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.describeKey("non-existent-id", REGION));
assertEquals("NotFoundException", ex.getErrorCode());
}
@Test
void scheduleKeyDeletion() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
KmsKey updated = kmsService.describeKey(key.getKeyId(), REGION);
assertEquals("PendingDeletion", updated.getKeyState());
assertTrue(updated.getDeletionDate() > 0);
}
@Test
void cancelKeyDeletion() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
kmsService.cancelKeyDeletion(key.getKeyId(), REGION);
KmsKey updated = kmsService.describeKey(key.getKeyId(), REGION);
assertEquals("Enabled", updated.getKeyState());
assertEquals(0, updated.getDeletionDate());
}
@Test
void createAlias() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/my-key", key.getKeyId(), REGION);
List<KmsAlias> aliases = kmsService.listAliases(REGION);
assertEquals(1, aliases.size());
assertEquals("alias/my-key", aliases.getFirst().getAliasName());
assertEquals(key.getKeyId(), aliases.getFirst().getTargetKeyId());
}
@Test
void createAliasWithoutPrefixThrows() {
KmsKey key = kmsService.createKey(null, REGION);
assertThrows(AwsException.class, () ->
kmsService.createAlias("my-key", key.getKeyId(), REGION));
}
@Test
void createAliasForNonExistentKeyThrows() {
assertThrows(AwsException.class, () ->
kmsService.createAlias("alias/test", "no-such-key", REGION));
}
@Test
void deleteAlias() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/to-delete", key.getKeyId(), REGION);
kmsService.deleteAlias("alias/to-delete", REGION);
assertTrue(kmsService.listAliases(REGION).isEmpty());
}
@Test
void deleteAliasNotFoundThrows() {
assertThrows(AwsException.class, () ->
kmsService.deleteAlias("alias/missing", REGION));
}
@Test
void resolveKeyByAlias() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/by-name", key.getKeyId(), REGION);
KmsKey resolved = kmsService.describeKey("alias/by-name", REGION);
assertEquals(key.getKeyId(), resolved.getKeyId());
}
@Test
void encryptAndDecrypt() {
KmsKey key = kmsService.createKey(null, REGION);
byte[] plaintext = "hello world".getBytes(StandardCharsets.UTF_8);
byte[] ciphertext = kmsService.encrypt(key.getKeyId(), plaintext, REGION);
byte[] decrypted = kmsService.decrypt(ciphertext, REGION);
assertArrayEquals(plaintext, decrypted);
}
@Test
void decryptInvalidCiphertextThrows() {
assertThrows(AwsException.class, () ->
kmsService.decrypt("not-valid-ciphertext".getBytes(StandardCharsets.UTF_8), REGION));
}
@Test
void signAndVerify() {
KmsKey key = kmsService.createKey(null, REGION);
byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);
byte[] sig = kmsService.sign(key.getKeyId(), message, "RSASSA_PSS_SHA_256", REGION);
assertTrue(kmsService.verify(key.getKeyId(), message, sig, "RSASSA_PSS_SHA_256", REGION));
}
@Test
void verifyWithWrongSignatureReturnsFalse() {
KmsKey key = kmsService.createKey(null, REGION);
byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);
kmsService.sign(key.getKeyId(), message, "RSASSA_PSS_SHA_256", REGION);
assertFalse(kmsService.verify(key.getKeyId(), message,
"wrong-sig".getBytes(StandardCharsets.UTF_8), "RSASSA_PSS_SHA_256", REGION));
}
@Test
void generateDataKey() {
KmsKey key = kmsService.createKey(null, REGION);
Map<String, Object> result = kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION);
assertNotNull(result.get("Plaintext"));
assertNotNull(result.get("CiphertextBlob"));
assertEquals(32, ((byte[]) result.get("Plaintext")).length);
}
@Test
void tagResource() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.tagResource(key.getKeyId(), Map.of("env", "test", "team", "platform"), REGION);
KmsKey updated = kmsService.describeKey(key.getKeyId(), REGION);
assertEquals("test", updated.getTags().get("env"));
assertEquals("platform", updated.getTags().get("team"));
}
@Test
void untagResource() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.tagResource(key.getKeyId(), Map.of("env", "test", "team", "platform"), REGION);
kmsService.untagResource(key.getKeyId(), List.of("env"), REGION);
KmsKey updated = kmsService.describeKey(key.getKeyId(), REGION);
assertFalse(updated.getTags().containsKey("env"));
assertTrue(updated.getTags().containsKey("team"));
}
}
@@ -0,0 +1,223 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for Lambda Event Source Mapping (ESM) endpoints.
* Requires an SQS queue and Lambda function to be created first.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class EsmIntegrationTest {
private static final String LAMBDA_BASE = "/2015-03-31";
private static final String SQS_BASE = "/";
private static final String FUNCTION_NAME = "esm-test-fn";
private static final String QUEUE_NAME = "esm-test-queue";
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
private static final String QUEUE_ARN =
"arn:aws:sqs:" + REGION + ":" + ACCOUNT_ID + ":" + QUEUE_NAME;
private static final String FUNCTION_ARN =
"arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:" + FUNCTION_NAME;
private static String esmUuid;
@Test
@Order(1)
void setupSqsQueue() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", QUEUE_NAME)
.formParam("Version", "2012-11-05")
.when()
.post(SQS_BASE)
.then()
.statusCode(200);
}
@Test
@Order(2)
void setupLambdaFunction() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Role": "arn:aws:iam::000000000000:role/lambda-role",
"Handler": "index.handler"
}
""".formatted(FUNCTION_NAME))
.when()
.post(LAMBDA_BASE + "/functions")
.then()
.statusCode(201)
.body("FunctionName", equalTo(FUNCTION_NAME));
}
@Test
@Order(3)
void createEventSourceMapping() {
String uuid = given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "%s",
"BatchSize": 5
}
""".formatted(FUNCTION_NAME, QUEUE_ARN))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(202)
.body("UUID", notNullValue())
.body("FunctionArn", equalTo(FUNCTION_ARN))
.body("EventSourceArn", equalTo(QUEUE_ARN))
.body("BatchSize", equalTo(5))
.body("State", equalTo("Enabled"))
.extract()
.path("UUID");
EsmIntegrationTest.esmUuid = uuid;
}
@Test
@Order(4)
void createEventSourceMappingForNonExistentFunction() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "does-not-exist",
"EventSourceArn": "%s"
}
""".formatted(QUEUE_ARN))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(404);
}
@Test
@Order(5)
void createEventSourceMappingUnsupportedArn() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"EventSourceArn": "arn:aws:sns:us-east-1:000000000000:my-topic"
}
""".formatted(FUNCTION_NAME))
.when()
.post(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(400);
}
@Test
@Order(6)
void getEventSourceMapping() {
given()
.when()
.get(LAMBDA_BASE + "/event-source-mappings/" + esmUuid)
.then()
.statusCode(200)
.body("UUID", equalTo(esmUuid))
.body("FunctionArn", equalTo(FUNCTION_ARN))
.body("BatchSize", equalTo(5))
.body("State", equalTo("Enabled"));
}
@Test
@Order(7)
void listEventSourceMappings() {
given()
.when()
.get(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(200)
.body("EventSourceMappings", hasSize(greaterThanOrEqualTo(1)))
.body("EventSourceMappings[0].UUID", notNullValue());
}
@Test
@Order(8)
void listEventSourceMappingsByFunction() {
given()
.queryParam("FunctionName", FUNCTION_ARN)
.when()
.get(LAMBDA_BASE + "/event-source-mappings")
.then()
.statusCode(200)
.body("EventSourceMappings", hasSize(greaterThanOrEqualTo(1)));
}
@Test
@Order(9)
void updateEventSourceMapping() {
given()
.contentType("application/json")
.body("{\"BatchSize\": 20, \"Enabled\": true}")
.when()
.put(LAMBDA_BASE + "/event-source-mappings/" + esmUuid)
.then()
.statusCode(202)
.body("BatchSize", equalTo(20))
.body("State", equalTo("Enabled"));
}
@Test
@Order(10)
void disableEventSourceMapping() {
given()
.contentType("application/json")
.body("{\"Enabled\": false}")
.when()
.put(LAMBDA_BASE + "/event-source-mappings/" + esmUuid)
.then()
.statusCode(202)
.body("State", equalTo("Disabled"));
}
@Test
@Order(11)
void getEventSourceMappingNotFound() {
given()
.when()
.get(LAMBDA_BASE + "/event-source-mappings/non-existent-uuid")
.then()
.statusCode(404);
}
@Test
@Order(12)
void deleteEventSourceMapping() {
given()
.when()
.delete(LAMBDA_BASE + "/event-source-mappings/" + esmUuid)
.then()
.statusCode(202)
.body("UUID", equalTo(esmUuid));
}
@Test
@Order(13)
void deleteEventSourceMappingNotFound() {
given()
.when()
.delete(LAMBDA_BASE + "/event-source-mappings/" + esmUuid)
.then()
.statusCode(404);
}
}
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class LambdaIntegrationTest {
private static final String BASE_PATH = "/2015-03-31";
@Test
@Order(1)
void createFunction() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "hello-world",
"Runtime": "nodejs20.x",
"Role": "arn:aws:iam::000000000000:role/lambda-role",
"Handler": "index.handler",
"Timeout": 30,
"MemorySize": 256,
"Description": "Integration test function"
}
""")
.when()
.post(BASE_PATH + "/functions")
.then()
.statusCode(201)
.body("FunctionName", equalTo("hello-world"))
.body("Runtime", equalTo("nodejs20.x"))
.body("Handler", equalTo("index.handler"))
.body("Timeout", equalTo(30))
.body("MemorySize", equalTo(256))
.body("State", equalTo("Active"))
.body("FunctionArn", containsString("hello-world"))
.body("RevisionId", notNullValue())
.body("Version", equalTo("$LATEST"));
}
@Test
@Order(2)
void createFunctionDuplicate_returns409() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "hello-world",
"Runtime": "nodejs20.x",
"Role": "arn:aws:iam::000000000000:role/lambda-role",
"Handler": "index.handler"
}
""")
.when()
.post(BASE_PATH + "/functions")
.then()
.statusCode(409);
}
@Test
@Order(3)
void getFunction() {
given()
.when()
.get(BASE_PATH + "/functions/hello-world")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("hello-world"))
.body("Configuration.State", equalTo("Active"))
.body("Code.RepositoryType", equalTo("S3"));
}
@Test
@Order(4)
void getFunction_notFound_returns404() {
given()
.when()
.get(BASE_PATH + "/functions/nonexistent-function")
.then()
.statusCode(404);
}
@Test
@Order(5)
void listFunctions() {
given()
.when()
.get(BASE_PATH + "/functions")
.then()
.statusCode(200)
.body("Functions", notNullValue())
.body("Functions.size()", greaterThanOrEqualTo(1))
.body("Functions.FunctionName", hasItem("hello-world"));
}
@Test
@Order(6)
void invokeDryRun() {
given()
.header("X-Amz-Invocation-Type", "DryRun")
.contentType("application/json")
.body("{\"key\": \"value\"}")
.when()
.post(BASE_PATH + "/functions/hello-world/invocations")
.then()
.statusCode(204)
.header("X-Amz-Executed-Version", equalTo("$LATEST"))
.header("X-Amz-Request-Id", notNullValue());
}
@Test
@Order(7)
void invokeNotFoundFunction_returns404() {
given()
.header("X-Amz-Invocation-Type", "DryRun")
.contentType("application/json")
.body("{}")
.when()
.post(BASE_PATH + "/functions/no-such-function/invocations")
.then()
.statusCode(404);
}
@Test
@Order(8)
void createFunctionMissingRole_returns400() {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "bad-fn",
"Runtime": "nodejs20.x",
"Handler": "index.handler"
}
""")
.when()
.post(BASE_PATH + "/functions")
.then()
.statusCode(400);
}
@Test
@Order(9)
void deleteFunction() {
given()
.when()
.delete(BASE_PATH + "/functions/hello-world")
.then()
.statusCode(204);
}
@Test
@Order(10)
void deletedFunctionNotFound() {
given()
.when()
.get(BASE_PATH + "/functions/hello-world")
.then()
.statusCode(404);
}
}
@@ -0,0 +1,136 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class LambdaServiceTest {
private static final String REGION = "us-east-1";
private LambdaService service;
@BeforeEach
void setUp() {
LambdaFunctionStore store = new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>());
WarmPool warmPool = new WarmPool();
CodeStore codeStore = new CodeStore(Path.of("target/test-data/lambda-code"));
ZipExtractor zipExtractor = new ZipExtractor();
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
service = new LambdaService(store, warmPool, codeStore, zipExtractor, regionResolver);
}
private Map<String, Object> baseRequest(String name) {
return new java.util.HashMap<>(Map.of(
"FunctionName", name,
"Runtime", "nodejs20.x",
"Role", "arn:aws:iam::000000000000:role/test-role",
"Handler", "index.handler",
"Timeout", 10,
"MemorySize", 256
));
}
@Test
void createFunctionSucceeds() {
LambdaFunction fn = service.createFunction(REGION, baseRequest("my-function"));
assertEquals("my-function", fn.getFunctionName());
assertEquals("nodejs20.x", fn.getRuntime());
assertEquals("index.handler", fn.getHandler());
assertEquals(10, fn.getTimeout());
assertEquals(256, fn.getMemorySize());
assertEquals("Active", fn.getState());
assertNotNull(fn.getFunctionArn());
assertTrue(fn.getFunctionArn().contains("my-function"));
assertNotNull(fn.getRevisionId());
}
@Test
void createFunctionFailsWhenMissingFunctionName() {
Map<String, Object> req = baseRequest("x");
req.remove("FunctionName");
AwsException ex = assertThrows(AwsException.class, () -> service.createFunction(REGION, req));
assertEquals("InvalidParameterValueException", ex.getErrorCode());
}
@Test
void createFunctionFailsWhenMissingRole() {
Map<String, Object> req = baseRequest("x");
req.remove("Role");
AwsException ex = assertThrows(AwsException.class, () -> service.createFunction(REGION, req));
assertEquals("InvalidParameterValueException", ex.getErrorCode());
}
@Test
void createFunctionFailsForDuplicate() {
service.createFunction(REGION, baseRequest("dup"));
AwsException ex = assertThrows(AwsException.class,
() -> service.createFunction(REGION, baseRequest("dup")));
assertEquals("ResourceConflictException", ex.getErrorCode());
assertEquals(409, ex.getHttpStatus());
}
@Test
void getFunctionReturnsCreatedFunction() {
service.createFunction(REGION, baseRequest("get-fn"));
LambdaFunction fn = service.getFunction(REGION, "get-fn");
assertEquals("get-fn", fn.getFunctionName());
}
@Test
void getFunctionThrows404WhenNotFound() {
AwsException ex = assertThrows(AwsException.class,
() -> service.getFunction(REGION, "nonexistent"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@Test
void listFunctionsReturnsAllInRegion() {
service.createFunction(REGION, baseRequest("fn-1"));
service.createFunction(REGION, baseRequest("fn-2"));
service.createFunction("eu-west-1", baseRequest("fn-3"));
List<LambdaFunction> functions = service.listFunctions(REGION);
assertEquals(2, functions.size());
assertTrue(functions.stream().anyMatch(f -> f.getFunctionName().equals("fn-1")));
assertTrue(functions.stream().anyMatch(f -> f.getFunctionName().equals("fn-2")));
}
@Test
void deleteFunctionRemovesIt() {
service.createFunction(REGION, baseRequest("del-fn"));
service.deleteFunction(REGION, "del-fn");
assertThrows(AwsException.class, () -> service.getFunction(REGION, "del-fn"));
}
@Test
void deleteFunctionThrows404WhenNotFound() {
AwsException ex = assertThrows(AwsException.class,
() -> service.deleteFunction(REGION, "ghost"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
}
@Test
void updateFunctionCodeUpdatesRevision() {
service.createFunction(REGION, baseRequest("update-fn"));
LambdaFunction original = service.getFunction(REGION, "update-fn");
String originalRevision = original.getRevisionId();
// Updating with no-op (no zip or image uri) still bumps revision
LambdaFunction updated = service.updateFunctionCode(REGION, "update-fn", Map.of());
assertNotEquals(originalRevision, updated.getRevisionId());
}
}
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class ImageResolverTest {
private final ImageResolver resolver = new ImageResolver();
@ParameterizedTest
@CsvSource({
"java21, public.ecr.aws/lambda/java:21",
"java17, public.ecr.aws/lambda/java:17",
"java11, public.ecr.aws/lambda/java:11",
"python3.13, public.ecr.aws/lambda/python:3.13",
"python3.12, public.ecr.aws/lambda/python:3.12",
"python3.11, public.ecr.aws/lambda/python:3.11",
"python3.10, public.ecr.aws/lambda/python:3.10",
"python3.9, public.ecr.aws/lambda/python:3.9",
"nodejs22.x, public.ecr.aws/lambda/nodejs:22",
"nodejs20.x, public.ecr.aws/lambda/nodejs:20",
"nodejs18.x, public.ecr.aws/lambda/nodejs:18",
"provided.al2023, public.ecr.aws/lambda/provided:al2023",
"provided.al2, public.ecr.aws/lambda/provided:al2"
})
void resolvesKnownRuntimes(String runtime, String expectedImage) {
assertEquals(expectedImage, resolver.resolve(runtime));
}
@Test
void passesThroughCustomImageWithSlash() {
String customImage = "123456789.dkr.ecr.us-east-1.amazonaws.com/my-function:latest";
assertEquals(customImage, resolver.resolve(customImage));
}
@Test
void passesThroughCustomImageWithColon() {
String customImage = "myrepo:latest";
assertEquals(customImage, resolver.resolve(customImage));
}
@Test
void throwsForUnknownRuntime() {
AwsException ex = assertThrows(AwsException.class, () -> resolver.resolve("dotnet8"));
assertEquals("InvalidParameterValueException", ex.getErrorCode());
}
@Test
void throwsForNullRuntime() {
assertThrows(AwsException.class, () -> resolver.resolve(null));
}
@Test
void throwsForBlankRuntime() {
assertThrows(AwsException.class, () -> resolver.resolve(" "));
}
}
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.net.URI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class PreSignedUrlIntegrationTest {
private static final String BUCKET = "presign-test-bucket";
@Inject
PreSignedUrlGenerator presignGenerator;
@Test
@Order(1)
void createBucketAndUploadObject() {
given().when().put("/" + BUCKET).then().statusCode(200);
given()
.body("presigned content")
.contentType("text/plain")
.when()
.put("/" + BUCKET + "/secret-file.txt")
.then()
.statusCode(200);
}
@Test
@Order(2)
void accessWithPresignedGetUrl() {
int port = io.restassured.RestAssured.port;
String fullBaseUrl = "http://localhost:" + port;
String presignedUrl = presignGenerator.generatePresignedUrl(
fullBaseUrl, BUCKET, "secret-file.txt", "GET", 3600);
// Extract path and query from the URL
URI uri = URI.create(presignedUrl);
given()
.when()
.get(uri.getRawPath() + "?" + uri.getRawQuery())
.then()
.statusCode(200)
.body(equalTo("presigned content"));
}
@Test
@Order(3)
void presignedUrlGeneratesValidStructure() {
String url = presignGenerator.generatePresignedUrl(
"http://localhost:4566", BUCKET, "file.txt", "GET", 300);
assertTrue(url.contains("X-Amz-Algorithm=AWS4-HMAC-SHA256"));
assertTrue(url.contains("X-Amz-Credential="));
assertTrue(url.contains("X-Amz-Date="));
assertTrue(url.contains("X-Amz-Expires=300"));
assertTrue(url.contains("X-Amz-SignedHeaders=host"));
assertTrue(url.contains("X-Amz-Signature="));
}
@Test
@Order(4)
void expiredPresignedUrlReturns403() {
// Create a URL with expired date by constructing manually
int port = io.restassured.RestAssured.port;
// Use an obviously expired date (year 2020)
String expiredPath = "/" + BUCKET + "/secret-file.txt"
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=test"
+ "&X-Amz-Date=20200101T000000Z"
+ "&X-Amz-Expires=1"
+ "&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=invalidsig";
given()
.when()
.get(expiredPath)
.then()
.statusCode(403)
.body(containsString("AccessDenied"));
}
@Test
@Order(5)
void presignedPutUrl() {
int port = io.restassured.RestAssured.port;
String fullBaseUrl = "http://localhost:" + port;
String url = presignGenerator.generatePresignedUrl(
fullBaseUrl, BUCKET, "uploaded-via-presign.txt", "PUT", 3600);
URI uri = URI.create(url);
given()
.body("uploaded via presigned PUT")
.when()
.put(uri.getRawPath() + "?" + uri.getRawQuery())
.then()
.statusCode(200);
// Verify the object was created
given()
.when()
.get("/" + BUCKET + "/uploaded-via-presign.txt")
.then()
.statusCode(200)
.body(equalTo("uploaded via presigned PUT"));
}
@Test
@Order(6)
void cleanUp() {
given().when().delete("/" + BUCKET + "/secret-file.txt").then().statusCode(204);
given().when().delete("/" + BUCKET + "/uploaded-via-presign.txt").then().statusCode(204);
given().when().delete("/" + BUCKET).then().statusCode(204);
}
}
@@ -0,0 +1,206 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3IntegrationTest {
@Test
@Order(1)
void createBucket() {
given()
.when()
.put("/test-bucket")
.then()
.statusCode(200);
}
@Test
@Order(2)
void createDuplicateBucketFails() {
given()
.when()
.put("/test-bucket")
.then()
.statusCode(409)
.body(containsString("BucketAlreadyOwnedByYou"));
}
@Test
@Order(3)
void listBuckets() {
given()
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("test-bucket"));
}
@Test
@Order(4)
void putObject() {
given()
.contentType("text/plain")
.body("Hello World from S3!")
.when()
.put("/test-bucket/greeting.txt")
.then()
.statusCode(200)
.header("ETag", notNullValue());
}
@Test
@Order(5)
void getObject() {
given()
.when()
.get("/test-bucket/greeting.txt")
.then()
.statusCode(200)
.header("ETag", notNullValue())
.header("Content-Length", notNullValue())
.body(equalTo("Hello World from S3!"));
}
@Test
@Order(6)
void headObject() {
given()
.when()
.head("/test-bucket/greeting.txt")
.then()
.statusCode(200)
.header("ETag", notNullValue())
.header("Content-Length", notNullValue());
}
@Test
@Order(7)
void getObjectNotFound() {
given()
.when()
.get("/test-bucket/nonexistent.txt")
.then()
.statusCode(404)
.body(containsString("NoSuchKey"));
}
@Test
@Order(8)
void putAnotherObject() {
given()
.contentType("application/json")
.body("{\"key\": \"value\"}")
.when()
.put("/test-bucket/data/config.json")
.then()
.statusCode(200);
}
@Test
@Order(9)
void listObjects() {
given()
.when()
.get("/test-bucket")
.then()
.statusCode(200)
.body(containsString("greeting.txt"))
.body(containsString("data/config.json"));
}
@Test
@Order(10)
void listObjectsWithPrefix() {
given()
.queryParam("prefix", "data/")
.when()
.get("/test-bucket")
.then()
.statusCode(200)
.body(containsString("data/config.json"))
.body(not(containsString("greeting.txt")));
}
@Test
@Order(11)
void copyObject() {
given()
.header("x-amz-copy-source", "/test-bucket/greeting.txt")
.when()
.put("/test-bucket/greeting-copy.txt")
.then()
.statusCode(200)
.body(containsString("CopyObjectResult"));
// Verify the copy
given()
.when()
.get("/test-bucket/greeting-copy.txt")
.then()
.statusCode(200)
.body(equalTo("Hello World from S3!"));
}
@Test
@Order(12)
void deleteObject() {
given()
.when()
.delete("/test-bucket/greeting-copy.txt")
.then()
.statusCode(204);
// Verify it's gone
given()
.when()
.get("/test-bucket/greeting-copy.txt")
.then()
.statusCode(404);
}
@Test
@Order(13)
void deleteNonEmptyBucketFails() {
given()
.when()
.delete("/test-bucket")
.then()
.statusCode(409)
.body(containsString("BucketNotEmpty"));
}
@Test
@Order(14)
void cleanupAndDeleteBucket() {
// Delete all objects
given().delete("/test-bucket/greeting.txt");
given().delete("/test-bucket/data/config.json");
// Now delete bucket
given()
.when()
.delete("/test-bucket")
.then()
.statusCode(204);
}
@Test
void getNonExistentBucket() {
given()
.when()
.get("/nonexistent-bucket")
.then()
.statusCode(404)
.body(containsString("NoSuchBucket"));
}
}
@@ -0,0 +1,164 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3MultipartIntegrationTest {
private static final String BUCKET = "multipart-test-bucket";
private static final String KEY = "large-file.bin";
private static String uploadId;
@Test
@Order(1)
void createBucket() {
given()
.when().put("/" + BUCKET)
.then().statusCode(200);
}
@Test
@Order(2)
void initiateMultipartUpload() {
uploadId = given()
.contentType("application/octet-stream")
.when()
.post("/" + BUCKET + "/" + KEY + "?uploads")
.then()
.statusCode(200)
.body(containsString("<UploadId>"))
.body(containsString("<Bucket>" + BUCKET + "</Bucket>"))
.body(containsString("<Key>" + KEY + "</Key>"))
.extract().xmlPath().getString(
"InitiateMultipartUploadResult.UploadId");
}
@Test
@Order(3)
void uploadPart1() {
given()
.body("Part1Data-Hello")
.when()
.put("/" + BUCKET + "/" + KEY + "?uploadId=" + uploadId + "&partNumber=1")
.then()
.statusCode(200)
.header("ETag", notNullValue());
}
@Test
@Order(4)
void uploadPart2() {
given()
.body("Part2Data-World")
.when()
.put("/" + BUCKET + "/" + KEY + "?uploadId=" + uploadId + "&partNumber=2")
.then()
.statusCode(200)
.header("ETag", notNullValue());
}
@Test
@Order(5)
void listMultipartUploads() {
given()
.when()
.get("/" + BUCKET + "?uploads")
.then()
.statusCode(200)
.body(containsString("<UploadId>" + uploadId + "</UploadId>"))
.body(containsString("<Key>" + KEY + "</Key>"));
}
@Test
@Order(6)
void completeMultipartUpload() {
String completeXml = """
<CompleteMultipartUpload>
<Part><PartNumber>1</PartNumber><ETag>etag1</ETag></Part>
<Part><PartNumber>2</PartNumber><ETag>etag2</ETag></Part>
</CompleteMultipartUpload>""";
given()
.contentType("application/xml")
.body(completeXml)
.when()
.post("/" + BUCKET + "/" + KEY + "?uploadId=" + uploadId)
.then()
.statusCode(200)
.body(containsString("<CompleteMultipartUploadResult"))
.body(containsString("<ETag>"))
.body(containsString("-2")); // Composite ETag ends with -2
}
@Test
@Order(7)
void getCompletedObject() {
given()
.when()
.get("/" + BUCKET + "/" + KEY)
.then()
.statusCode(200)
.body(equalTo("Part1Data-HelloPart2Data-World"));
}
@Test
@Order(8)
void multipartUploadNoLongerListed() {
given()
.when()
.get("/" + BUCKET + "?uploads")
.then()
.statusCode(200)
.body(not(containsString("<UploadId>")));
}
@Test
@Order(9)
void abortMultipartUpload() {
// Initiate new upload
String newUploadId = given()
.when()
.post("/" + BUCKET + "/abort-test.bin?uploads")
.then()
.statusCode(200)
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
// Upload a part
given()
.body("some data")
.when()
.put("/" + BUCKET + "/abort-test.bin?uploadId=" + newUploadId + "&partNumber=1")
.then()
.statusCode(200);
// Abort
given()
.when()
.delete("/" + BUCKET + "/abort-test.bin?uploadId=" + newUploadId)
.then()
.statusCode(204);
// Verify upload is gone
given()
.when()
.get("/" + BUCKET + "?uploads")
.then()
.statusCode(200)
.body(not(containsString(newUploadId)));
}
@Test
@Order(10)
void cleanUp() {
given().when().delete("/" + BUCKET + "/" + KEY).then().statusCode(204);
given().when().delete("/" + BUCKET).then().statusCode(204);
}
}
@@ -0,0 +1,135 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class S3MultipartServiceTest {
private S3Service s3Service;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir);
s3Service.createBucket("test-bucket");
}
@Test
void initiateMultipartUpload() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "large-file.bin", "application/octet-stream");
assertNotNull(upload.getUploadId());
assertEquals("test-bucket", upload.getBucket());
assertEquals("large-file.bin", upload.getKey());
assertNotNull(upload.getInitiated());
}
@Test
void initiateMultipartUploadNonExistentBucket() {
assertThrows(AwsException.class, () ->
s3Service.initiateMultipartUpload("no-bucket", "key", null));
}
@Test
void uploadPart() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", null);
byte[] data = "part-1-data".getBytes(StandardCharsets.UTF_8);
String eTag = s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 1, data);
assertNotNull(eTag);
assertTrue(eTag.startsWith("\""));
assertEquals(1, upload.getParts().size());
}
@Test
void uploadPartInvalidNumber() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", null);
assertThrows(AwsException.class, () ->
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 0, new byte[1]));
assertThrows(AwsException.class, () ->
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 10001, new byte[1]));
}
@Test
void uploadPartNonExistentUpload() {
assertThrows(AwsException.class, () ->
s3Service.uploadPart("test-bucket", "file.bin", "bad-id", 1, new byte[1]));
}
@Test
void completeMultipartUpload() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", "text/plain");
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 1, "part1".getBytes());
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 2, "part2".getBytes());
S3Object result = s3Service.completeMultipartUpload("test-bucket", "file.bin",
upload.getUploadId(), List.of(1, 2));
assertNotNull(result);
assertEquals("text/plain", result.getContentType());
// Verify the data is concatenated
S3Object fetched = s3Service.getObject("test-bucket", "file.bin");
assertEquals("part1part2", new String(fetched.getData()));
// Composite ETag should end with -2 (number of parts)
assertTrue(result.getETag().endsWith("-2\""), "ETag should be composite: " + result.getETag());
}
@Test
void completeMultipartUploadMissingPart() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", null);
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 1, "part1".getBytes());
assertThrows(AwsException.class, () ->
s3Service.completeMultipartUpload("test-bucket", "file.bin",
upload.getUploadId(), List.of(1, 2)));
}
@Test
void abortMultipartUpload() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", null);
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 1, "data".getBytes());
s3Service.abortMultipartUpload("test-bucket", "file.bin", upload.getUploadId());
// Upload should no longer exist
assertThrows(AwsException.class, () ->
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 2, "data".getBytes()));
}
@Test
void listMultipartUploads() {
s3Service.initiateMultipartUpload("test-bucket", "file1.bin", null);
s3Service.initiateMultipartUpload("test-bucket", "file2.bin", null);
List<MultipartUpload> uploads = s3Service.listMultipartUploads("test-bucket");
assertEquals(2, uploads.size());
}
@Test
void listMultipartUploadsEmpty() {
List<MultipartUpload> uploads = s3Service.listMultipartUploads("test-bucket");
assertTrue(uploads.isEmpty());
}
@Test
void completeMultipartUploadCleansUp() {
MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "file.bin", null);
s3Service.uploadPart("test-bucket", "file.bin", upload.getUploadId(), 1, "data".getBytes());
s3Service.completeMultipartUpload("test-bucket", "file.bin", upload.getUploadId(), List.of(1));
// Should no longer be in active uploads
List<MultipartUpload> uploads = s3Service.listMultipartUploads("test-bucket");
assertTrue(uploads.isEmpty());
}
}
@@ -0,0 +1,135 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class S3SelectIntegrationTest {
@Test
void select_withWhereClause() {
String bucket = "select-bucket";
String key = "data.csv";
String csvData = "name,age\nAlice,30\nBob,25\nCharlie,35";
// 1. Create bucket
given()
.header("Host", bucket + ".localhost")
.when()
.put("/")
.then()
.statusCode(200);
// 2. Put object
given()
.header("Host", bucket + ".localhost")
.body(csvData)
.when()
.put("/" + key)
.then()
.statusCode(200);
// 3. Select with WHERE clause
String requestXml = """
<?xml version="1.0" encoding="UTF-8"?>
<SelectObjectContentRequest>
<Expression>SELECT * FROM S3Object s WHERE s.age > 30</Expression>
<ExpressionType>SQL</ExpressionType>
<InputSerialization>
<CSV>
<FileHeaderInfo>USE</FileHeaderInfo>
</CSV>
</InputSerialization>
<OutputSerialization>
<CSV/>
</OutputSerialization>
</SelectObjectContentRequest>
""";
given()
.header("Host", bucket + ".localhost")
.queryParam("select", "")
.queryParam("select-type", "2")
.body(requestXml)
.when()
.post("/" + key)
.then()
.statusCode(200)
.body(containsString("Charlie,35"))
.body(not(containsString("Alice,30")))
.body(not(containsString("Bob,25")));
}
@Test
void select_withProjection() {
String bucket = "select-bucket-proj";
String key = "data.csv";
String csvData = "name,age,city\nAlice,30,New York\nBob,25,London";
given().header("Host", bucket + ".localhost").when().put("/").then().statusCode(200);
given().header("Host", bucket + ".localhost").body(csvData).when().put("/" + key).then().statusCode(200);
String requestXml = """
<?xml version="1.0" encoding="UTF-8"?>
<SelectObjectContentRequest>
<Expression>SELECT name, city FROM S3Object</Expression>
<ExpressionType>SQL</ExpressionType>
<InputSerialization><CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV></InputSerialization>
<OutputSerialization><CSV/></OutputSerialization>
</SelectObjectContentRequest>
""";
given()
.header("Host", bucket + ".localhost")
.queryParam("select", "")
.queryParam("select-type", "2")
.body(requestXml)
.when()
.post("/" + key)
.then()
.statusCode(200)
.body(containsString("Alice,New York"))
.body(containsString("Bob,London"))
.body(not(containsString("30")))
.body(not(containsString("25")));
}
@Test
void select_withLimit() {
String bucket = "select-bucket-limit";
String key = "data.csv";
String csvData = "name,age\nAlice,30\nBob,25\nCharlie,35";
given().header("Host", bucket + ".localhost").when().put("/").then().statusCode(200);
given().header("Host", bucket + ".localhost").body(csvData).when().put("/" + key).then().statusCode(200);
String requestXml = """
<?xml version="1.0" encoding="UTF-8"?>
<SelectObjectContentRequest>
<Expression>SELECT * FROM S3Object LIMIT 2</Expression>
<ExpressionType>SQL</ExpressionType>
<InputSerialization><CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV></InputSerialization>
<OutputSerialization><CSV/></OutputSerialization>
</SelectObjectContentRequest>
""";
given()
.header("Host", bucket + ".localhost")
.queryParam("select", "")
.queryParam("select-type", "2")
.body(requestXml)
.when()
.post("/" + key)
.then()
.statusCode(200)
.body(containsString("Alice,30"))
.body(containsString("Bob,25"))
.body(not(containsString("Charlie,35")));
}
}
@@ -0,0 +1,207 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class S3ServiceTest {
@TempDir
Path tempDir;
private S3Service s3Service;
@BeforeEach
void setUp() {
Path dataRoot = tempDir.resolve("s3");
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot);
}
@Test
void createBucket() {
Bucket bucket = s3Service.createBucket("test-bucket");
assertEquals("test-bucket", bucket.getName());
assertNotNull(bucket.getCreationDate());
}
@Test
void createDuplicateBucketThrows() {
s3Service.createBucket("test-bucket");
assertThrows(AwsException.class, () -> s3Service.createBucket("test-bucket"));
}
@Test
void deleteBucket() {
s3Service.createBucket("test-bucket");
s3Service.deleteBucket("test-bucket");
assertThrows(AwsException.class, () -> s3Service.deleteBucket("test-bucket"));
}
@Test
void deleteNonEmptyBucketThrows() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "hello".getBytes(), "text/plain", null);
assertThrows(AwsException.class, () -> s3Service.deleteBucket("test-bucket"));
}
@Test
void deleteNonExistentBucketThrows() {
assertThrows(AwsException.class, () -> s3Service.deleteBucket("nonexistent"));
}
@Test
void listBuckets() {
s3Service.createBucket("bucket-a");
s3Service.createBucket("bucket-b");
List<Bucket> buckets = s3Service.listBuckets();
assertEquals(2, buckets.size());
}
@Test
void putAndGetObject() {
s3Service.createBucket("test-bucket");
byte[] data = "Hello World".getBytes(StandardCharsets.UTF_8);
S3Object put = s3Service.putObject("test-bucket", "greeting.txt", data, "text/plain", null);
assertNotNull(put.getETag());
assertEquals(11, put.getSize());
S3Object got = s3Service.getObject("test-bucket", "greeting.txt");
assertArrayEquals(data, got.getData());
assertEquals("text/plain", got.getContentType());
}
@Test
void putObjectWritesFileToDisk() {
s3Service.createBucket("test-bucket");
byte[] data = "file content".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("test-bucket", "docs/readme.txt", data, "text/plain", null);
Path filePath = tempDir.resolve("s3/test-bucket/docs/readme.txt");
assertTrue(Files.exists(filePath));
assertArrayEquals(data, assertDoesNotThrow(() -> Files.readAllBytes(filePath)));
}
@Test
void deleteObjectRemovesFileFromDisk() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "data".getBytes(), null, null);
Path filePath = tempDir.resolve("s3/test-bucket/file.txt");
assertTrue(Files.exists(filePath));
s3Service.deleteObject("test-bucket", "file.txt");
assertFalse(Files.exists(filePath));
}
@Test
void deleteBucketRemovesDirectory() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "data".getBytes(), null, null);
s3Service.deleteObject("test-bucket", "file.txt");
s3Service.deleteBucket("test-bucket");
assertFalse(Files.exists(tempDir.resolve("s3/test-bucket")));
}
@Test
void getObjectNotFoundThrows() {
s3Service.createBucket("test-bucket");
AwsException ex = assertThrows(AwsException.class, () ->
s3Service.getObject("test-bucket", "missing.txt"));
assertEquals("NoSuchKey", ex.getErrorCode());
}
@Test
void putObjectToNonExistentBucketThrows() {
assertThrows(AwsException.class, () ->
s3Service.putObject("nonexistent", "file.txt", "data".getBytes(), null, null));
}
@Test
void deleteObject() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "data".getBytes(), null, null);
s3Service.deleteObject("test-bucket", "file.txt");
assertThrows(AwsException.class, () ->
s3Service.getObject("test-bucket", "file.txt"));
}
@Test
void listObjects() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "docs/a.txt", "a".getBytes(), null, null);
s3Service.putObject("test-bucket", "docs/b.txt", "b".getBytes(), null, null);
s3Service.putObject("test-bucket", "images/pic.jpg", "img".getBytes(), null, null);
List<S3Object> all = s3Service.listObjects("test-bucket", null, null, 1000);
assertEquals(3, all.size());
List<S3Object> docs = s3Service.listObjects("test-bucket", "docs/", null, 1000);
assertEquals(2, docs.size());
}
@Test
void listObjectsInNonExistentBucketThrows() {
assertThrows(AwsException.class, () ->
s3Service.listObjects("nonexistent", null, null, 100));
}
@Test
void copyObject() {
s3Service.createBucket("source-bucket");
s3Service.createBucket("dest-bucket");
s3Service.putObject("source-bucket", "original.txt", "content".getBytes(), "text/plain", null);
S3Object copy = s3Service.copyObject("source-bucket", "original.txt", "dest-bucket", "copy.txt");
assertNotNull(copy.getETag());
S3Object retrieved = s3Service.getObject("dest-bucket", "copy.txt");
assertArrayEquals("content".getBytes(), retrieved.getData());
// Verify file exists on disk for the copy
assertTrue(Files.exists(tempDir.resolve("s3/dest-bucket/copy.txt")));
}
@Test
void copyObjectSameBucket() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "original.txt", "data".getBytes(), null, null);
s3Service.copyObject("test-bucket", "original.txt", "test-bucket", "copy.txt");
assertNotNull(s3Service.getObject("test-bucket", "copy.txt"));
}
@Test
void headObject() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "hello".getBytes(), "text/plain", null);
S3Object head = s3Service.headObject("test-bucket", "file.txt");
assertEquals(5, head.getSize());
assertEquals("text/plain", head.getContentType());
}
@Test
void putObjectOverwrites() {
s3Service.createBucket("test-bucket");
s3Service.putObject("test-bucket", "file.txt", "v1".getBytes(), null, null);
s3Service.putObject("test-bucket", "file.txt", "v2".getBytes(), null, null);
S3Object obj = s3Service.getObject("test-bucket", "file.txt");
assertArrayEquals("v2".getBytes(), obj.getData());
}
}
@@ -0,0 +1,181 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3VersioningIntegrationTest {
private static final String BUCKET = "versioning-int-test";
private static String versionId1;
private static String versionId2;
@Test
@Order(1)
void createBucket() {
given().when().put("/" + BUCKET).then().statusCode(200);
}
@Test
@Order(2)
void versioningNotEnabledByDefault() {
given()
.when()
.get("/" + BUCKET + "?versioning")
.then()
.statusCode(200)
.body(containsString("<VersioningConfiguration"))
.body(not(containsString("<Status>")));
}
@Test
@Order(3)
void enableVersioning() {
String xml = "<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>";
given()
.body(xml)
.when()
.put("/" + BUCKET + "?versioning")
.then()
.statusCode(200);
}
@Test
@Order(4)
void getVersioningStatus() {
given()
.when()
.get("/" + BUCKET + "?versioning")
.then()
.statusCode(200)
.body(containsString("<Status>Enabled</Status>"));
}
@Test
@Order(5)
void putObjectReturnsVersionId() {
versionId1 = given()
.body("Version 1 content")
.contentType("text/plain")
.when()
.put("/" + BUCKET + "/test.txt")
.then()
.statusCode(200)
.header("x-amz-version-id", notNullValue())
.extract().header("x-amz-version-id");
}
@Test
@Order(6)
void putObjectSecondVersion() {
versionId2 = given()
.body("Version 2 content")
.contentType("text/plain")
.when()
.put("/" + BUCKET + "/test.txt")
.then()
.statusCode(200)
.header("x-amz-version-id", notNullValue())
.extract().header("x-amz-version-id");
assertNotEquals(versionId1, versionId2);
}
@Test
@Order(7)
void getLatestVersion() {
given()
.when()
.get("/" + BUCKET + "/test.txt")
.then()
.statusCode(200)
.header("x-amz-version-id", versionId2)
.body(equalTo("Version 2 content"));
}
@Test
@Order(8)
void getSpecificVersion() {
given()
.when()
.get("/" + BUCKET + "/test.txt?versionId=" + versionId1)
.then()
.statusCode(200)
.header("x-amz-version-id", versionId1)
.body(equalTo("Version 1 content"));
}
@Test
@Order(9)
void listObjectVersions() {
given()
.when()
.get("/" + BUCKET + "?versions")
.then()
.statusCode(200)
.body(containsString("<ListVersionsResult"))
.body(containsString("<Version>"))
.body(containsString(versionId1))
.body(containsString(versionId2));
}
@Test
@Order(10)
void deleteCreatesMarker() {
given()
.when()
.delete("/" + BUCKET + "/test.txt")
.then()
.statusCode(204)
.header("x-amz-delete-marker", "true");
}
@Test
@Order(11)
void getAfterDeleteReturns404() {
given()
.when()
.get("/" + BUCKET + "/test.txt")
.then()
.statusCode(404);
}
@Test
@Order(12)
void getSpecificVersionAfterDelete() {
// Specific version should still be accessible
given()
.when()
.get("/" + BUCKET + "/test.txt?versionId=" + versionId1)
.then()
.statusCode(200)
.body(equalTo("Version 1 content"));
}
@Test
@Order(13)
void listVersionsShowsDeleteMarker() {
given()
.when()
.get("/" + BUCKET + "?versions")
.then()
.statusCode(200)
.body(containsString("<DeleteMarker>"));
}
@Test
@Order(14)
void cleanUp() {
// Delete specific versions permanently
given().when().delete("/" + BUCKET + "/test.txt?versionId=" + versionId1).then().statusCode(204);
given().when().delete("/" + BUCKET + "/test.txt?versionId=" + versionId2).then().statusCode(204);
}
}
@@ -0,0 +1,171 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class S3VersioningServiceTest {
private S3Service s3Service;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir);
s3Service.createBucket("versioned-bucket");
}
@Test
void enableVersioning() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
assertEquals("Enabled", s3Service.getBucketVersioning("versioned-bucket"));
}
@Test
void suspendVersioning() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
s3Service.putBucketVersioning("versioned-bucket", "Suspended");
assertEquals("Suspended", s3Service.getBucketVersioning("versioned-bucket"));
}
@Test
void versioningNotEnabledByDefault() {
assertNull(s3Service.getBucketVersioning("versioned-bucket"));
}
@Test
void invalidVersioningStatus() {
assertThrows(AwsException.class, () ->
s3Service.putBucketVersioning("versioned-bucket", "Invalid"));
}
@Test
void putObjectWithVersioning() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
S3Object obj = s3Service.putObject("versioned-bucket", "test.txt",
"v1".getBytes(StandardCharsets.UTF_8), "text/plain", null);
assertNotNull(obj.getVersionId());
}
@Test
void putObjectWithoutVersioningHasNoVersionId() {
S3Object obj = s3Service.putObject("versioned-bucket", "test.txt",
"data".getBytes(StandardCharsets.UTF_8), "text/plain", null);
assertNull(obj.getVersionId());
}
@Test
void multipleVersionsOfSameKey() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
S3Object v1 = s3Service.putObject("versioned-bucket", "test.txt",
"version1".getBytes(StandardCharsets.UTF_8), "text/plain", null);
S3Object v2 = s3Service.putObject("versioned-bucket", "test.txt",
"version2".getBytes(StandardCharsets.UTF_8), "text/plain", null);
assertNotEquals(v1.getVersionId(), v2.getVersionId());
// Get latest should return v2
S3Object latest = s3Service.getObject("versioned-bucket", "test.txt");
assertEquals("version2", new String(latest.getData()));
// Get specific version should return v1
S3Object specific = s3Service.getObject("versioned-bucket", "test.txt", v1.getVersionId());
assertEquals("version1", new String(specific.getData()));
}
@Test
void deleteCreatesMarkerWhenVersioned() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
s3Service.putObject("versioned-bucket", "test.txt",
"data".getBytes(StandardCharsets.UTF_8), "text/plain", null);
S3Object result = s3Service.deleteObject("versioned-bucket", "test.txt");
assertNotNull(result);
assertTrue(result.isDeleteMarker());
// Get should now fail with NoSuchKey
assertThrows(AwsException.class, () ->
s3Service.getObject("versioned-bucket", "test.txt"));
}
@Test
void deleteWithVersionIdIsPermanent() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
S3Object v1 = s3Service.putObject("versioned-bucket", "test.txt",
"v1".getBytes(StandardCharsets.UTF_8), "text/plain", null);
s3Service.deleteObject("versioned-bucket", "test.txt", v1.getVersionId());
// The specific version should be gone
assertThrows(AwsException.class, () ->
s3Service.getObject("versioned-bucket", "test.txt", v1.getVersionId()));
}
@Test
void getObjectAfterDeleteMarkerWithSpecificVersion() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
S3Object v1 = s3Service.putObject("versioned-bucket", "test.txt",
"v1-data".getBytes(StandardCharsets.UTF_8), "text/plain", null);
// Delete creates marker
s3Service.deleteObject("versioned-bucket", "test.txt");
// Latest is gone
assertThrows(AwsException.class, () ->
s3Service.getObject("versioned-bucket", "test.txt"));
// But specific version still accessible
S3Object retrieved = s3Service.getObject("versioned-bucket", "test.txt", v1.getVersionId());
assertEquals("v1-data", new String(retrieved.getData()));
}
@Test
void listObjectVersions() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
s3Service.putObject("versioned-bucket", "test.txt",
"v1".getBytes(StandardCharsets.UTF_8), "text/plain", null);
s3Service.putObject("versioned-bucket", "test.txt",
"v2".getBytes(StandardCharsets.UTF_8), "text/plain", null);
List<S3Object> versions = s3Service.listObjectVersions("versioned-bucket", null, 100);
assertEquals(2, versions.size());
}
@Test
void listObjectVersionsIncludesDeleteMarkers() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
s3Service.putObject("versioned-bucket", "test.txt",
"data".getBytes(StandardCharsets.UTF_8), "text/plain", null);
s3Service.deleteObject("versioned-bucket", "test.txt");
List<S3Object> versions = s3Service.listObjectVersions("versioned-bucket", null, 100);
assertEquals(2, versions.size());
assertTrue(versions.stream().anyMatch(S3Object::isDeleteMarker));
}
@Test
void listObjectsExcludesDeleteMarkers() {
s3Service.putBucketVersioning("versioned-bucket", "Enabled");
s3Service.putObject("versioned-bucket", "keep.txt",
"keep".getBytes(StandardCharsets.UTF_8), "text/plain", null);
s3Service.putObject("versioned-bucket", "delete-me.txt",
"data".getBytes(StandardCharsets.UTF_8), "text/plain", null);
s3Service.deleteObject("versioned-bucket", "delete-me.txt");
List<S3Object> objects = s3Service.listObjects("versioned-bucket", null, null, 100);
assertEquals(1, objects.size());
assertEquals("keep.txt", objects.get(0).getKey());
}
}
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.secretsmanager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class SecretsManagerServiceTest {
private static final String REGION = "us-east-1";
private SecretsManagerService service;
@BeforeEach
void setUp() {
service = new SecretsManagerService(new InMemoryStorage<>(), 30);
}
@Test
void createSecret() {
Secret secret = service.createSecret("my-secret", "super-secret-value",
null, "A test secret", null, null, REGION);
assertNotNull(secret.getArn());
assertEquals("my-secret", secret.getName());
assertEquals("A test secret", secret.getDescription());
assertNotNull(secret.getCurrentVersionId());
}
@Test
void createSecretDuplicateThrows() {
service.createSecret("my-secret", "value1", null, null, null, null, REGION);
assertThrows(AwsException.class, () ->
service.createSecret("my-secret", "value2", null, null, null, null, REGION));
}
@Test
void getSecretValue() {
service.createSecret("db-password", "s3cr3t", null, null, null, null, REGION);
SecretVersion version = service.getSecretValue("db-password", null, null, REGION);
assertEquals("s3cr3t", version.getSecretString());
assertNotNull(version.getVersionId());
assertTrue(version.getVersionStages().contains("AWSCURRENT"));
}
@Test
void getSecretValueNotFoundThrows() {
assertThrows(AwsException.class, () ->
service.getSecretValue("missing", null, null, REGION));
}
@Test
void putSecretValueRotatesVersion() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION);
SecretVersion current = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
assertEquals("v2", current.getSecretString());
SecretVersion previous = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION);
assertEquals("v1", previous.getSecretString());
}
@Test
void putSecretValueOnDeletedSecretThrows() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.deleteSecret("my-secret", null, true, REGION);
assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION));
}
@Test
void describeSecret() {
service.createSecret("my-secret", "value", null, "desc", null, null, REGION);
Secret described = service.describeSecret("my-secret", REGION);
assertEquals("my-secret", described.getName());
assertEquals("desc", described.getDescription());
}
@Test
void updateSecret() {
service.createSecret("my-secret", "value", null, "old desc", null, null, REGION);
service.updateSecret("my-secret", "new desc", null, REGION);
Secret updated = service.describeSecret("my-secret", REGION);
assertEquals("new desc", updated.getDescription());
}
@Test
void listSecrets() {
service.createSecret("secret-1", "v1", null, null, null, null, REGION);
service.createSecret("secret-2", "v2", null, null, null, null, REGION);
service.createSecret("other-region", "v3", null, null, null, null, "eu-west-1");
List<Secret> secrets = service.listSecrets(REGION);
assertEquals(2, secrets.size());
}
@Test
void listSecretsExcludesDeleted() {
service.createSecret("active", "v1", null, null, null, null, REGION);
service.createSecret("deleted", "v2", null, null, null, null, REGION);
service.deleteSecret("deleted", 0, true, REGION);
List<Secret> secrets = service.listSecrets(REGION);
assertEquals(1, secrets.size());
assertEquals("active", secrets.getFirst().getName());
}
@Test
void deleteSecretWithRecoveryWindow() {
service.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret deleted = service.deleteSecret("my-secret", 7, false, REGION);
assertNotNull(deleted.getDeletedDate());
// The secret still exists but marked deleted
assertThrows(AwsException.class, () ->
service.getSecretValue("my-secret", null, null, REGION));
}
@Test
void forceDeleteSecret() {
service.createSecret("my-secret", "value", null, null, null, null, REGION);
service.deleteSecret("my-secret", null, true, REGION);
assertThrows(AwsException.class, () ->
service.describeSecret("my-secret", REGION));
}
@Test
void rotateSecret() {
service.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret rotated = service.rotateSecret("my-secret",
"arn:aws:lambda:us-east-1:000000000000:function:rotate",
Map.of("AutomaticallyAfterDays", 30), true, REGION);
assertTrue(rotated.isRotationEnabled());
}
@Test
void tagAndUntagResource() {
service.createSecret("my-secret", "value", null, null, null,
List.of(new Secret.Tag("env", "prod")), REGION);
service.tagResource("my-secret", List.of(new Secret.Tag("team", "platform")), REGION);
Secret secret = service.describeSecret("my-secret", REGION);
List<String> keys = secret.getTags().stream().map(Secret.Tag::key).toList();
assertTrue(keys.containsAll(List.of("env", "team")));
service.untagResource("my-secret", List.of("env"), REGION);
secret = service.describeSecret("my-secret", REGION);
assertEquals(1, secret.getTags().size());
assertEquals("team", secret.getTags().getFirst().key());
}
@Test
void tagResourceUpserts() {
service.createSecret("my-secret", "value", null, null, null,
List.of(new Secret.Tag("env", "dev")), REGION);
service.tagResource("my-secret", List.of(new Secret.Tag("env", "prod")), REGION);
Secret secret = service.describeSecret("my-secret", REGION);
assertEquals(1, secret.getTags().size());
assertEquals("prod", secret.getTags().getFirst().value());
}
@Test
void listSecretVersionIds() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION);
Map<String, List<String>> versions = service.listSecretVersionIds("my-secret", REGION);
assertEquals(2, versions.size());
long currentCount = versions.values().stream()
.filter(stages -> stages.contains("AWSCURRENT")).count();
assertEquals(1, currentCount);
}
@Test
void getSecretValueByVersionId() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
SecretVersion v1 = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
String v1Id = v1.getVersionId();
service.putSecretValue("my-secret", "v2", null, REGION);
SecretVersion fetched = service.getSecretValue("my-secret", v1Id, null, REGION);
assertEquals("v1", fetched.getSecretString());
}
}
@@ -0,0 +1,294 @@
package io.github.hectorvent.floci.services.sns;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for SNS via the query (form-encoded) protocol.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SnsIntegrationTest {
private static String topicArn;
private static String subscriptionArn;
private static String sqsQueueUrl;
@Test
@Order(1)
void createQueue_forFanout() {
sqsQueueUrl = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "sns-fanout-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<QueueUrl>"))
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
}
@Test
@Order(2)
void createTopic() {
topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "integration-test-topic")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<TopicArn>"))
.body(containsString("integration-test-topic"))
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
}
@Test
@Order(3)
void createTopic_idempotent() {
String arn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "integration-test-topic")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
assert arn.equals(topicArn);
}
@Test
@Order(4)
void listTopics() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListTopics")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("integration-test-topic"));
}
@Test
@Order(5)
void getTopicAttributes() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTopicAttributes")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("TopicArn"))
.body(containsString("SubscriptionsConfirmed"));
}
@Test
@Order(6)
void subscribe_toSqsQueue() {
subscriptionArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "sqs")
.formParam("Endpoint", sqsQueueUrl)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"))
.extract().xmlPath()
.getString("SubscribeResponse.SubscribeResult.SubscriptionArn");
}
@Test
@Order(7)
void listSubscriptionsByTopic() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListSubscriptionsByTopic")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("sqs"))
.body(containsString("sns-fanout-queue"));
}
@Test
@Order(8)
void listSubscriptions() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListSubscriptions")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("integration-test-topic"));
}
@Test
@Order(9)
void publish_fanOutToSqsSubscriber() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "Hello from SNS!")
.formParam("Subject", "Test message")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
// Verify the message arrived in the SQS queue
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", sqsQueueUrl)
.formParam("MaxNumberOfMessages", "1")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("Hello from SNS!"))
.body(containsString("Notification"));
}
@Test
@Order(10)
void publishBatch() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "PublishBatch")
.formParam("TopicArn", topicArn)
.formParam("PublishBatchRequestEntries.member.1.Id", "msg1")
.formParam("PublishBatchRequestEntries.member.1.Message", "Batch message 1")
.formParam("PublishBatchRequestEntries.member.2.Id", "msg2")
.formParam("PublishBatchRequestEntries.member.2.Message", "Batch message 2")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Id>msg1</Id>"))
.body(containsString("<Id>msg2</Id>"))
.body(containsString("<MessageId>"));
}
@Test
@Order(11)
void tagResource() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "TagResource")
.formParam("ResourceArn", topicArn)
.formParam("Tags.member.1.Key", "env")
.formParam("Tags.member.1.Value", "test")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(11)
void listTagsForResource() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListTagsForResource")
.formParam("ResourceArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("env"))
.body(containsString("test"));
}
@Test
@Order(12)
void setTopicAttributes() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SetTopicAttributes")
.formParam("TopicArn", topicArn)
.formParam("AttributeName", "DisplayName")
.formParam("AttributeValue", "My Test Topic")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(13)
void unsubscribe() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Unsubscribe")
.formParam("SubscriptionArn", subscriptionArn)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListSubscriptionsByTopic")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("sns-fanout-queue")));
}
@Test
@Order(14)
void deleteTopic() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteTopic")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListTopics")
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("integration-test-topic")));
}
@Test
@Order(15)
void unsupportedAction_returns400() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UnknownSnsAction")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("UnsupportedOperation"));
}
}
@@ -0,0 +1,75 @@
package io.github.hectorvent.floci.services.sns;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
class SnsLambdaIntegrationTest {
@Test
void publish_toLambdaSubscriber() {
// 1. Create a Lambda function using the REST API (skipping code to bypass validation)
String functionName = "sns-subscriber-fn";
String lambdaRequest = String.format(
"{\"FunctionName\":\"%s\",\"Runtime\":\"nodejs18.x\",\"Handler\":\"index.handler\",\"Role\":\"arn:aws:iam::000000000000:role/lambda-role\"}",
functionName
);
given()
.contentType("application/json")
.body(lambdaRequest)
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(201);
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:" + functionName;
// 2. Create a Topic
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "lambda-test-topic")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
// 3. Subscribe Lambda to Topic
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "lambda")
.formParam("Endpoint", functionArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
// 4. Publish message
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "{\"foo\":\"bar\"}")
.formParam("Subject", "Lambda Test")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
// Note: Actual invocation check would require mocking the Docker/Executor,
// but here we just want to see if it reaches the delivery logic without crashing.
}
}
@@ -0,0 +1,202 @@
package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.sns.model.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class SnsServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String BASE_URL = "http://localhost:4566";
private SnsService snsService;
@BeforeEach
void setUp() {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
// SqsService and LambdaService are null — delivery failures are caught and logged; fanout is covered by IT
snsService = new SnsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
regionResolver,
null,
null
);
}
@Test
void createTopic_returnsTopicWithArn() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
assertNotNull(topic);
assertEquals("my-topic", topic.getName());
assertEquals("arn:aws:sns:us-east-1:000000000000:my-topic", topic.getTopicArn());
}
@Test
void createTopic_idempotent() {
Topic first = snsService.createTopic("my-topic", null, null, REGION);
Topic second = snsService.createTopic("my-topic", null, null, REGION);
assertEquals(first.getTopicArn(), second.getTopicArn());
}
@Test
void createTopic_requiresName() {
assertThrows(AwsException.class, () -> snsService.createTopic(null, null, null, REGION));
assertThrows(AwsException.class, () -> snsService.createTopic("", null, null, REGION));
}
@Test
void listTopics_returnsCreatedTopics() {
snsService.createTopic("topic-a", null, null, REGION);
snsService.createTopic("topic-b", null, null, REGION);
List<Topic> topics = snsService.listTopics(REGION);
assertEquals(2, topics.size());
}
@Test
void listTopics_isolatedByRegion() {
snsService.createTopic("topic-east", null, null, "us-east-1");
snsService.createTopic("topic-west", null, null, "us-west-2");
assertEquals(1, snsService.listTopics("us-east-1").size());
assertEquals(1, snsService.listTopics("us-west-2").size());
}
@Test
void deleteTopic_removesTopicAndSubscriptions() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
snsService.subscribe(topic.getTopicArn(), "sqs", "http://queue-url", REGION);
snsService.deleteTopic(topic.getTopicArn(), REGION);
assertTrue(snsService.listTopics(REGION).isEmpty());
assertTrue(snsService.listSubscriptions(REGION).isEmpty());
}
@Test
void deleteTopic_throwsForMissing() {
assertThrows(AwsException.class,
() -> snsService.deleteTopic("arn:aws:sns:us-east-1:000000000000:nonexistent", REGION));
}
@Test
void getTopicAttributes_returnsAttributes() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
Map<String, String> attrs = snsService.getTopicAttributes(topic.getTopicArn(), REGION);
assertTrue(attrs.containsKey("TopicArn"));
assertEquals(topic.getTopicArn(), attrs.get("TopicArn"));
assertTrue(attrs.containsKey("SubscriptionsConfirmed"));
assertEquals("0", attrs.get("SubscriptionsConfirmed"));
}
@Test
void subscribe_returnsSubscription() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
Subscription sub = snsService.subscribe(topic.getTopicArn(), "sqs",
"http://localhost:4566/000000000000/my-queue", REGION);
assertNotNull(sub.getSubscriptionArn());
assertEquals(topic.getTopicArn(), sub.getTopicArn());
assertEquals("sqs", sub.getProtocol());
assertEquals(ACCOUNT, sub.getOwner());
}
@Test
void subscribe_throwsForMissingTopic() {
assertThrows(AwsException.class,
() -> snsService.subscribe("arn:aws:sns:us-east-1:000000000000:nonexistent",
"sqs", "http://queue", REGION));
}
@Test
void subscribe_requiresProtocol() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
assertThrows(AwsException.class,
() -> snsService.subscribe(topic.getTopicArn(), null, "http://queue", REGION));
}
@Test
void unsubscribe_removesSubscription() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
Subscription sub = snsService.subscribe(topic.getTopicArn(), "sqs",
"http://queue", REGION);
snsService.unsubscribe(sub.getSubscriptionArn(), REGION);
assertTrue(snsService.listSubscriptions(REGION).isEmpty());
}
@Test
void listSubscriptionsByTopic_filtersCorrectly() {
Topic topicA = snsService.createTopic("topic-a", null, null, REGION);
Topic topicB = snsService.createTopic("topic-b", null, null, REGION);
snsService.subscribe(topicA.getTopicArn(), "sqs", "http://queue1", REGION);
snsService.subscribe(topicA.getTopicArn(), "sqs", "http://queue2", REGION);
snsService.subscribe(topicB.getTopicArn(), "sqs", "http://queue3", REGION);
assertEquals(2, snsService.listSubscriptionsByTopic(topicA.getTopicArn(), REGION).size());
assertEquals(1, snsService.listSubscriptionsByTopic(topicB.getTopicArn(), REGION).size());
}
@Test
void publish_withSqsSubscriber_returnsMessageId() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
snsService.subscribe(topic.getTopicArn(), "sqs",
BASE_URL + "/" + ACCOUNT + "/fanout-queue", REGION);
// Fanout delivery is exercised — message ID returned confirms success
String messageId = snsService.publish(topic.getTopicArn(), null, "Hello SNS!", null, REGION);
assertNotNull(messageId);
}
@Test
void publish_requiresTopicArn() {
assertThrows(AwsException.class,
() -> snsService.publish(null, null, "msg", null, REGION));
}
@Test
void publish_requiresMessage() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
assertThrows(AwsException.class,
() -> snsService.publish(topic.getTopicArn(), null, null, null, REGION));
}
@Test
void publish_noSubscribers_succeeds() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
String messageId = snsService.publish(topic.getTopicArn(), null, "Hello!", null, REGION);
assertNotNull(messageId);
}
@Test
void tagResource_and_listTags() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
snsService.tagResource(topic.getTopicArn(), Map.of("env", "test"), REGION);
Map<String, String> tags = snsService.listTagsForResource(topic.getTopicArn(), REGION);
assertEquals("test", tags.get("env"));
}
@Test
void untagResource_removesTags() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
snsService.tagResource(topic.getTopicArn(), Map.of("env", "test", "team", "ops"), REGION);
snsService.untagResource(topic.getTopicArn(), List.of("env"), REGION);
Map<String, String> tags = snsService.listTagsForResource(topic.getTopicArn(), REGION);
assertFalse(tags.containsKey("env"));
assertEquals("ops", tags.get("team"));
}
@Test
void subscriptionsConfirmed_countsCorrectly() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);
snsService.subscribe(topic.getTopicArn(), "sqs", "http://queue1", REGION);
snsService.subscribe(topic.getTopicArn(), "sqs", "http://queue2", REGION);
Map<String, String> attrs = snsService.getTopicAttributes(topic.getTopicArn(), REGION);
assertEquals("2", attrs.get("SubscriptionsConfirmed"));
}
}
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.sqs;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SqsFifoIntegrationTest {
private static String queueUrl;
@Test
@Order(1)
void createFifoQueue() {
queueUrl = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "fifo-test.fifo")
.formParam("Attribute.1.Name", "FifoQueue")
.formParam("Attribute.1.Value", "true")
.formParam("Attribute.2.Name", "ContentBasedDeduplication")
.formParam("Attribute.2.Value", "true")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<QueueUrl>"))
.body(containsString("fifo-test.fifo"))
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
}
@Test
@Order(2)
void sendMessageToFifoQueue() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "FIFO message 1")
.formParam("MessageGroupId", "group-a")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"))
.body(containsString("<SequenceNumber>"));
}
@Test
@Order(3)
void sendMessageWithExplicitDedup() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "FIFO message 2")
.formParam("MessageGroupId", "group-a")
.formParam("MessageDeduplicationId", "explicit-dedup-1")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SequenceNumber>"));
}
@Test
@Order(4)
void sendDuplicateMessageIsIdempotent() {
// Send same dedup ID — should return same message ID
String msgId1 = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "dedup-test")
.formParam("MessageGroupId", "group-b")
.formParam("MessageDeduplicationId", "unique-dedup-1")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("SendMessageResponse.SendMessageResult.MessageId");
String msgId2 = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "dedup-test")
.formParam("MessageGroupId", "group-b")
.formParam("MessageDeduplicationId", "unique-dedup-1")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("SendMessageResponse.SendMessageResult.MessageId");
// Same message ID returned
org.junit.jupiter.api.Assertions.assertEquals(msgId1, msgId2);
}
@Test
@Order(5)
void receiveMessageIncludesFifoAttributes() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "10")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("MessageGroupId"))
.body(containsString("SequenceNumber"));
}
@Test
@Order(6)
void sendToFifoWithoutGroupIdFails() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "should fail")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("MissingParameter"));
}
@Test
@Order(7)
void getFifoQueueAttributes() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", queueUrl)
.formParam("AttributeName.1", "All")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("FifoQueue"))
.body(containsString("ContentBasedDeduplication"));
}
@Test
@Order(8)
void deleteFifoQueue() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue")
.formParam("QueueUrl", queueUrl)
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,218 @@
package io.github.hectorvent.floci.services.sqs;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SqsIntegrationTest {
private static String queueUrl;
@Test
@Order(1)
void createQueue() {
queueUrl = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "integration-test-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<QueueUrl>"))
.body(containsString("integration-test-queue"))
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
}
@Test
@Order(2)
void getQueueUrl() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", "integration-test-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("integration-test-queue"));
}
@Test
@Order(3)
void listQueues() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("integration-test-queue"));
}
@Test
@Order(4)
void sendMessage() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "Hello from integration test!")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"))
.body(containsString("<MD5OfMessageBody>"));
}
@Test
@Order(5)
void receiveMessage() {
String receiptHandle = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("Hello from integration test!"))
.body(containsString("<ReceiptHandle>"))
.extract().xmlPath().getString(
"ReceiveMessageResponse.ReceiveMessageResult.Message.ReceiptHandle");
// Store for delete test — use static field
SqsIntegrationTest.receiptHandle = receiptHandle;
}
private static String receiptHandle;
@Test
@Order(6)
void deleteMessage() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteMessage")
.formParam("QueueUrl", queueUrl)
.formParam("ReceiptHandle", receiptHandle)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<DeleteMessageResponse>"));
}
@Test
@Order(7)
void receiveMessageAfterDeleteReturnsEmpty() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.formParam("VisibilityTimeout", "0")
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("<Message>")));
}
@Test
@Order(8)
void sendAndPurgeQueue() {
// Send some messages
for (int i = 0; i < 3; i++) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "purge-msg-" + i)
.when()
.post("/");
}
// Purge
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "PurgeQueue")
.formParam("QueueUrl", queueUrl)
.when()
.post("/")
.then()
.statusCode(200);
// Verify empty
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "10")
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("<Message>")));
}
@Test
@Order(9)
void getQueueAttributes() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", queueUrl)
.formParam("AttributeName.1", "All")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Attribute>"))
.body(containsString("QueueArn"));
}
@Test
@Order(10)
void deleteQueue() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue")
.formParam("QueueUrl", queueUrl)
.when()
.post("/")
.then()
.statusCode(200);
// Verify it's gone
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", "integration-test-queue")
.when()
.post("/")
.then()
.statusCode(400);
}
@Test
void unsupportedAction() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UnsupportedAction")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("UnsupportedOperation"));
}
}
@@ -0,0 +1,291 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class SqsServiceTest {
private SqsService sqsService;
private static final String BASE_URL = "http://localhost:4566";
@BeforeEach
void setUp() {
sqsService = new SqsService(new InMemoryStorage<>(), 30, 262144, BASE_URL);
}
@Test
void createQueue() {
Queue queue = sqsService.createQueue("test-queue", null);
assertEquals("test-queue", queue.getQueueName());
assertEquals(BASE_URL + "/000000000000/test-queue", queue.getQueueUrl());
assertNotNull(queue.getCreatedTimestamp());
}
@Test
void createQueueIsIdempotent() {
Queue q1 = sqsService.createQueue("test-queue", null);
Queue q2 = sqsService.createQueue("test-queue", null);
assertEquals(q1.getQueueUrl(), q2.getQueueUrl());
}
@Test
void createQueueWithAttributes() {
Queue queue = sqsService.createQueue("test-queue",
Map.of("VisibilityTimeout", "60"));
assertEquals("60", queue.getAttributes().get("VisibilityTimeout"));
}
@Test
void deleteQueue() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.deleteQueue(queue.getQueueUrl());
assertThrows(AwsException.class, () ->
sqsService.getQueueUrl("test-queue"));
}
@Test
void deleteQueueNotFound() {
assertThrows(AwsException.class, () ->
sqsService.deleteQueue(BASE_URL + "/000000000000/nonexistent"));
}
@Test
void listQueues() {
sqsService.createQueue("alpha-queue", null);
sqsService.createQueue("beta-queue", null);
sqsService.createQueue("alpha-other", null);
List<Queue> all = sqsService.listQueues(null);
assertEquals(3, all.size());
List<Queue> alpha = sqsService.listQueues("alpha");
assertEquals(2, alpha.size());
}
@Test
void getQueueUrl() {
sqsService.createQueue("my-queue", null);
String url = sqsService.getQueueUrl("my-queue");
assertEquals(BASE_URL + "/000000000000/my-queue", url);
}
@Test
void getQueueUrlNotFound() {
assertThrows(AwsException.class, () ->
sqsService.getQueueUrl("nonexistent"));
}
@Test
void sendAndReceiveMessage() {
Queue queue = sqsService.createQueue("test-queue", null);
Message sent = sqsService.sendMessage(queue.getQueueUrl(), "Hello World", 0);
assertNotNull(sent.getMessageId());
assertNotNull(sent.getMd5OfBody());
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
assertEquals(1, received.size());
assertEquals("Hello World", received.getFirst().getBody());
assertNotNull(received.getFirst().getReceiptHandle());
assertEquals(1, received.getFirst().getReceiveCount());
}
@Test
void receiveMessageReturnsEmptyWhenNoMessages() {
Queue queue = sqsService.createQueue("empty-queue", null);
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
assertTrue(received.isEmpty());
}
@Test
void messageBecomesInvisibleAfterReceive() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "msg1", 0);
// First receive should get the message
List<Message> first = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
assertEquals(1, first.size());
// Second receive should get nothing (message is invisible)
List<Message> second = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
assertTrue(second.isEmpty());
}
@Test
void deleteMessage() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "to-delete", 0);
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
sqsService.deleteMessage(queue.getQueueUrl(), received.getFirst().getReceiptHandle());
// Message should be permanently gone; even after visibility would expire
// it shouldn't reappear
List<Message> afterDelete = sqsService.receiveMessage(queue.getQueueUrl(), 1, 0, 0);
assertTrue(afterDelete.isEmpty());
}
@Test
void deleteMessageInvalidHandle() {
Queue queue = sqsService.createQueue("test-queue", null);
assertThrows(AwsException.class, () ->
sqsService.deleteMessage(queue.getQueueUrl(), "invalid-handle"));
}
@Test
void sendMessageToNonExistentQueue() {
assertThrows(AwsException.class, () ->
sqsService.sendMessage(BASE_URL + "/000000000000/nonexistent", "msg", 0));
}
@Test
void receiveMultipleMessages() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "msg1", 0);
sqsService.sendMessage(queue.getQueueUrl(), "msg2", 0);
sqsService.sendMessage(queue.getQueueUrl(), "msg3", 0);
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 3, 30, 0);
assertEquals(3, received.size());
}
@Test
void purgeQueue() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "msg1", 0);
sqsService.sendMessage(queue.getQueueUrl(), "msg2", 0);
sqsService.purgeQueue(queue.getQueueUrl());
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 10, 30, 0);
assertTrue(received.isEmpty());
}
@Test
void changeMessageVisibility() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "msg1", 0);
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
String receiptHandle = received.getFirst().getReceiptHandle();
// Set visibility to 0 — message becomes visible immediately
sqsService.changeMessageVisibility(queue.getQueueUrl(), receiptHandle, 0);
List<Message> reReceived = sqsService.receiveMessage(queue.getQueueUrl(), 1, 30, 0);
assertEquals(1, reReceived.size());
}
@Test
void getQueueAttributes() {
Queue queue = sqsService.createQueue("test-queue", null);
sqsService.sendMessage(queue.getQueueUrl(), "msg", 0);
Map<String, String> attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"));
assertNotNull(attrs.get("QueueArn"));
assertNotNull(attrs.get("CreatedTimestamp"));
assertEquals("1", attrs.get("ApproximateNumberOfMessages"));
}
// --- FIFO Queue Tests ---
@Test
void createFifoQueue() {
Queue queue = sqsService.createQueue("test-queue.fifo", null);
assertTrue(queue.isFifo());
assertEquals("true", queue.getAttributes().get("FifoQueue"));
assertEquals("false", queue.getAttributes().get("ContentBasedDeduplication"));
}
@Test
void createFifoQueueWithExplicitAttribute() {
Queue queue = sqsService.createQueue("test-queue.fifo",
Map.of("FifoQueue", "true", "ContentBasedDeduplication", "true"));
assertTrue(queue.isFifo());
assertEquals("true", queue.getAttributes().get("ContentBasedDeduplication"));
}
@Test
void createFifoQueueWithoutSuffixFails() {
assertThrows(AwsException.class, () ->
sqsService.createQueue("test-queue", Map.of("FifoQueue", "true")));
}
@Test
void sendMessageToFifoQueueRequiresGroupId() {
Queue queue = sqsService.createQueue("test.fifo",
Map.of("ContentBasedDeduplication", "true"));
assertThrows(AwsException.class, () ->
sqsService.sendMessage(queue.getQueueUrl(), "msg", 0, null, null));
}
@Test
void sendMessageToFifoQueueWithContentBasedDedup() {
Queue queue = sqsService.createQueue("test.fifo",
Map.of("ContentBasedDeduplication", "true"));
Message msg = sqsService.sendMessage(queue.getQueueUrl(), "Hello FIFO", 0, "group1", null);
assertNotNull(msg.getMessageId());
assertEquals("group1", msg.getMessageGroupId());
assertTrue(msg.getSequenceNumber() > 0);
assertNotNull(msg.getMessageDeduplicationId());
}
@Test
void sendMessageToFifoQueueWithExplicitDedupId() {
Queue queue = sqsService.createQueue("test.fifo", null);
Message msg = sqsService.sendMessage(queue.getQueueUrl(), "msg", 0, "group1", "dedup-1");
assertEquals("dedup-1", msg.getMessageDeduplicationId());
}
@Test
void fifoDeduplicationReturnsExistingMessage() {
Queue queue = sqsService.createQueue("test.fifo", null);
Message msg1 = sqsService.sendMessage(queue.getQueueUrl(), "msg", 0, "group1", "dedup-1");
Message msg2 = sqsService.sendMessage(queue.getQueueUrl(), "msg", 0, "group1", "dedup-1");
assertEquals(msg1.getMessageId(), msg2.getMessageId());
// Only one message should be in the queue
List<Message> received = sqsService.receiveMessage(queue.getQueueUrl(), 10, 30, 0);
assertEquals(1, received.size());
}
@Test
void fifoQueueReceiveRespectsGroupOrdering() {
Queue queue = sqsService.createQueue("test.fifo", null);
sqsService.sendMessage(queue.getQueueUrl(), "g1-msg1", 0, "group1", "d1");
sqsService.sendMessage(queue.getQueueUrl(), "g1-msg2", 0, "group1", "d2");
sqsService.sendMessage(queue.getQueueUrl(), "g2-msg1", 0, "group2", "d3");
// First receive: should get one message per group (first from each)
List<Message> first = sqsService.receiveMessage(queue.getQueueUrl(), 10, 30, 0);
assertEquals(2, first.size());
assertEquals("g1-msg1", first.get(0).getBody());
assertEquals("g2-msg1", first.get(1).getBody());
// Second receive: group1 and group2 both have in-flight messages, so nothing returned
List<Message> second = sqsService.receiveMessage(queue.getQueueUrl(), 10, 30, 0);
assertTrue(second.isEmpty());
// Delete the group1 message, then receive again — should get g1-msg2
sqsService.deleteMessage(queue.getQueueUrl(), first.get(0).getReceiptHandle());
List<Message> third = sqsService.receiveMessage(queue.getQueueUrl(), 10, 30, 0);
assertEquals(1, third.size());
assertEquals("g1-msg2", third.get(0).getBody());
}
@Test
void fifoQueueRequiresDedupIdWhenContentBasedDisabled() {
Queue queue = sqsService.createQueue("test.fifo", null);
// ContentBasedDeduplication is false by default
assertThrows(AwsException.class, () ->
sqsService.sendMessage(queue.getQueueUrl(), "msg", 0, "group1", null));
}
}
@@ -0,0 +1,252 @@
package io.github.hectorvent.floci.services.ssm;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SsmIntegrationTest {
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
@BeforeAll
static void configureRestAssured() {
RestAssured.config = RestAssured.config().encoderConfig(
EncoderConfig.encoderConfig()
.encodeContentTypeAs(SSM_CONTENT_TYPE, ContentType.TEXT));
}
@Test
@Order(1)
void putParameter() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/app/db/host",
"Value": "localhost",
"Type": "String"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Version", equalTo(1));
}
@Test
@Order(2)
void getParameter() {
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/app/db/host",
"WithDecryption": true
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameter.Name", equalTo("/app/db/host"))
.body("Parameter.Value", equalTo("localhost"))
.body("Parameter.Type", equalTo("String"))
.body("Parameter.Version", equalTo(1));
}
@Test
@Order(3)
void putParameterOverwrite() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/app/db/host",
"Value": "db.example.com",
"Type": "String",
"Overwrite": true
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Version", equalTo(2));
}
@Test
@Order(4)
void putParameterWithoutOverwriteFails() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/app/db/host",
"Value": "other",
"Type": "String"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterAlreadyExists"));
}
@Test
@Order(5)
void getParameterNotFound() {
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/nonexistent" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterNotFound"));
}
@Test
@Order(6)
void getParametersByPath() {
// Add more parameters
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/app/db/port", "Value": "5432", "Type": "String" }
""")
.when()
.post("/");
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/app/cache/host", "Value": "redis", "Type": "String" }
""")
.when()
.post("/");
// Query by path
given()
.header("X-Amz-Target", "AmazonSSM.GetParametersByPath")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Path": "/app/db", "Recursive": true }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameters.size()", equalTo(2));
}
@Test
@Order(7)
void getParameters() {
given()
.header("X-Amz-Target", "AmazonSSM.GetParameters")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Names": ["/app/db/host", "/app/db/port", "/missing"] }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameters.size()", equalTo(2));
}
@Test
@Order(8)
void getParameterHistory() {
given()
.header("X-Amz-Target", "AmazonSSM.GetParameterHistory")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/app/db/host" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameters.size()", greaterThanOrEqualTo(2));
}
@Test
@Order(9)
void deleteParameter() {
given()
.header("X-Amz-Target", "AmazonSSM.DeleteParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/app/cache/host" }
""")
.when()
.post("/")
.then()
.statusCode(200);
// Verify it's gone
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/app/cache/host" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterNotFound"));
}
@Test
@Order(10)
void deleteParameters() {
given()
.header("X-Amz-Target", "AmazonSSM.DeleteParameters")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Names": ["/app/db/host", "/app/db/port", "/missing"] }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("DeletedParameters.size()", equalTo(2));
}
@Test
void unsupportedOperation() {
given()
.header("X-Amz-Target", "AmazonSSM.UnsupportedAction")
.contentType(SSM_CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("UnsupportedOperation"));
}
}
@@ -0,0 +1,139 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class SsmServiceTest {
private SsmService ssmService;
@BeforeEach
void setUp() {
ssmService = new SsmService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
5
);
}
@Test
void putAndGetParameter() {
ssmService.putParameter("/app/db/host", "localhost", "String", null, false);
Parameter param = ssmService.getParameter("/app/db/host");
assertEquals("/app/db/host", param.getName());
assertEquals("localhost", param.getValue());
assertEquals("String", param.getType());
assertEquals(1, param.getVersion());
assertNotNull(param.getLastModifiedDate());
}
@Test
void putParameterOverwrite() {
ssmService.putParameter("/app/key", "v1", "String", null, false);
ssmService.putParameter("/app/key", "v2", "String", null, true);
Parameter param = ssmService.getParameter("/app/key");
assertEquals("v2", param.getValue());
assertEquals(2, param.getVersion());
}
@Test
void putParameterWithoutOverwriteThrows() {
ssmService.putParameter("/app/key", "v1", "String", null, false);
assertThrows(AwsException.class, () ->
ssmService.putParameter("/app/key", "v2", "String", null, false));
}
@Test
void getParameterNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.getParameter("/nonexistent"));
assertEquals("ParameterNotFound", ex.getErrorCode());
}
@Test
void getParameters() {
ssmService.putParameter("/a", "1", "String", null, false);
ssmService.putParameter("/b", "2", "String", null, false);
ssmService.putParameter("/c", "3", "String", null, false);
List<Parameter> params = ssmService.getParameters(List.of("/a", "/c", "/missing"));
assertEquals(2, params.size());
}
@Test
void getParametersByPathRecursive() {
ssmService.putParameter("/app/db/host", "localhost", "String", null, false);
ssmService.putParameter("/app/db/port", "5432", "String", null, false);
ssmService.putParameter("/app/db/nested/deep", "value", "String", null, false);
ssmService.putParameter("/app/cache/host", "redis", "String", null, false);
List<Parameter> results = ssmService.getParametersByPath("/app/db", true);
assertEquals(3, results.size());
}
@Test
void getParametersByPathNonRecursive() {
ssmService.putParameter("/app/db/host", "localhost", "String", null, false);
ssmService.putParameter("/app/db/port", "5432", "String", null, false);
ssmService.putParameter("/app/db/nested/deep", "value", "String", null, false);
List<Parameter> results = ssmService.getParametersByPath("/app/db", false);
assertEquals(2, results.size());
}
@Test
void deleteParameter() {
ssmService.putParameter("/app/key", "value", "String", null, false);
ssmService.deleteParameter("/app/key");
assertThrows(AwsException.class, () -> ssmService.getParameter("/app/key"));
}
@Test
void deleteParameterNotFoundThrows() {
assertThrows(AwsException.class, () -> ssmService.deleteParameter("/missing"));
}
@Test
void deleteParameters() {
ssmService.putParameter("/a", "1", "String", null, false);
ssmService.putParameter("/b", "2", "String", null, false);
List<String> deleted = ssmService.deleteParameters(List.of("/a", "/missing"));
assertEquals(1, deleted.size());
assertEquals("/a", deleted.getFirst());
}
@Test
void getParameterHistory() {
ssmService.putParameter("/app/key", "v1", "String", null, false);
ssmService.putParameter("/app/key", "v2", "String", null, true);
ssmService.putParameter("/app/key", "v3", "String", null, true);
List<ParameterHistory> history = ssmService.getParameterHistory("/app/key");
assertEquals(3, history.size());
assertEquals("v1", history.get(0).getValue());
assertEquals("v3", history.get(2).getValue());
}
@Test
void parameterHistoryIsTrimmedToMax() {
for (int i = 1; i <= 7; i++) {
ssmService.putParameter("/app/key", "v" + i, "String", null, i == 1 ? false : true);
}
List<ParameterHistory> history = ssmService.getParameterHistory("/app/key");
assertEquals(5, history.size());
assertEquals("v3", history.get(0).getValue());
assertEquals("v7", history.get(4).getValue());
}
}