fix(s3): validate notification destinations before storing configuration (#4747)

* fix(s3): validate notification destinations before storing configuration

* test(s3): consume validation events before POST notifications

* fix(s3): preserve bucket lifecycle during notification validation

* fix(s3): enforce SQS queue policies for notifications

* fix(s3): align notification validation with IAM enforcement

* fix(test): stub IAM config for S3 failure delivery

* fix(s3): validate cross-account SNS without test publish

* fix(sns): recognize legacy topics during destination validation

* docs(s3): describe cross-account notification validation

* fix(s3): skip cross-account SNS notification test publishes
This commit is contained in:
XuJian authored and GitHub committed 2026-10-01 11:35:16 -04:00
1 parent bc2592e300
commit b2dd5665db
14 files changed
+1051 -23

No files matched your search

@@ -895,6 +895,9 @@ class DynamoDbStreamsEventSourcePollerTest {
EmulatorConfig.S3ServiceConfig s3Config = mock(EmulatorConfig.S3ServiceConfig.class);
when(s3Config.globalBucketNamespace()).thenReturn(globalBucketNamespace);
when(config.services().s3()).thenReturn(s3Config);
EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
when(iamConfig.enforcementEnabled()).thenReturn(false);
when(config.services().iam()).thenReturn(iamConfig);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenAnswer(
@@ -2219,6 +2219,7 @@ class S3IntegrationTest {
""";
given()
.header("x-amz-skip-destination-validation", "true")
.contentType("application/xml")
.queryParam("notification", "")
.body(xml)
@@ -2266,6 +2267,7 @@ class S3IntegrationTest {
""";
given()
.header("x-amz-skip-destination-validation", "true")
.contentType("application/xml")
.queryParam("notification", "")
.body(xml)
@@ -2313,6 +2315,7 @@ class S3IntegrationTest {
""";
given()
.header("x-amz-skip-destination-validation", "true")
.contentType("application/xml")
.queryParam("notification", "")
.body(xml)
@@ -2370,6 +2373,19 @@ class S3IntegrationTest {
.then()
.statusCode(200);
given()
.header("Authorization", sqsAuth)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.when()
.post("/")
.then()
.statusCode(200)
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body",
containsString("s3:TestEvent"));
given()
.contentType("text/plain")
.body("hello")
@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class S3NotificationDestinationIamEnforcementIntegrationTest {
private static final String REGION = "us-east-1";
private static final String BUCKET_ACCOUNT = "000000000000";
private static final String OTHER_ACCOUNT = "000000000002";
@Inject SqsService sqsService;
@InjectSpy SnsService snsService;
@Inject ObjectMapper objectMapper;
private String bucket;
@BeforeEach
void createBucket() {
bucket = "notification-enforced-" + UUID.randomUUID().toString().substring(0, 8);
given().header("Authorization", authorization(BUCKET_ACCOUNT, "s3"))
.when().put("/" + bucket).then().statusCode(200);
}
@AfterEach
void removeBucket() {
given().header("Authorization", authorization(BUCKET_ACCOUNT, "s3"))
.when().delete("/" + bucket).then().statusCode(204);
}
@Test
void crossAccountQueueIsValidatedWithoutReceivingTestMessage() throws Exception {
String otherQueueName = "notification-other-" + UUID.randomUUID().toString().substring(0, 8);
String ownQueueName = "notification-own-" + UUID.randomUUID().toString().substring(0, 8);
String otherQueueUrl = createQueue(OTHER_ACCOUNT, otherQueueName);
String ownQueueUrl = createQueue(BUCKET_ACCOUNT, ownQueueName);
String otherQueueArn = queueArn(OTHER_ACCOUNT, otherQueueName);
String ownQueueArn = queueArn(BUCKET_ACCOUNT, ownQueueName);
try {
putNotification(otherQueueArn).statusCode(200);
assertTrue(sqsService.receiveMessage(otherQueueUrl, 1, 0, 0, REGION).isEmpty());
getNotification().body(containsString(otherQueueArn));
String missingQueueArn = queueArn(OTHER_ACCOUNT, "notification-missing-" + UUID.randomUUID());
putNotification(missingQueueArn).statusCode(400)
.body(containsString("The destination queue does not exist"));
getNotification().body(containsString(otherQueueArn))
.body(not(containsString(missingQueueArn)));
assertTrue(sqsService.receiveMessage(otherQueueUrl, 1, 0, 0, REGION).isEmpty());
putNotification(ownQueueArn).statusCode(200);
List<Message> ownMessages = sqsService.receiveMessage(ownQueueUrl, 1, 0, 0, REGION);
assertFalse(ownMessages.isEmpty());
JsonNode testEvent = objectMapper.readTree(ownMessages.getFirst().getBody());
assertEquals("s3:TestEvent", testEvent.path("Event").asText());
assertFalse(testEvent.has("Records"));
assertTrue(sqsService.receiveMessage(otherQueueUrl, 1, 0, 0, REGION).isEmpty());
} finally {
deleteQueue(BUCKET_ACCOUNT, ownQueueUrl);
deleteQueue(OTHER_ACCOUNT, otherQueueUrl);
}
}
@Test
void crossAccountTopicIsValidatedWithoutPublishingTestMessage() {
String otherTopicName = "notification-other-" + UUID.randomUUID().toString().substring(0, 8);
String ownTopicName = "notification-own-" + UUID.randomUUID().toString().substring(0, 8);
String otherTopicArn = createTopic(OTHER_ACCOUNT, otherTopicName);
String ownTopicArn = createTopic(BUCKET_ACCOUNT, ownTopicName);
try {
assertTrue(snsService.topicExists(otherTopicArn, REGION));
putTopicNotification(otherTopicArn).statusCode(200);
verify(snsService, never()).publish(eq(otherTopicArn), isNull(), anyString(),
eq("Amazon S3 Notification"), eq(REGION));
getNotification().body(containsString(otherTopicArn));
String missingTopicArn = topicArn(OTHER_ACCOUNT, "notification-missing-" + UUID.randomUUID());
putTopicNotification(missingTopicArn).statusCode(400)
.body(containsString("The destination topic does not exist"));
getNotification().body(containsString(otherTopicArn))
.body(not(containsString(missingTopicArn)));
putTopicNotification(ownTopicArn).statusCode(200);
verify(snsService).publish(eq(ownTopicArn), isNull(), anyString(),
eq("Amazon S3 Notification"), eq(REGION));
} finally {
deleteTopic(BUCKET_ACCOUNT, ownTopicArn);
deleteTopic(OTHER_ACCOUNT, otherTopicArn);
}
}
private static String createQueue(String accountId, String queueName) {
return given().header("Authorization", authorization(accountId, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue").formParam("QueueName", queueName)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
}
private static void deleteQueue(String accountId, String queueUrl) {
given().header("Authorization", authorization(accountId, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue").formParam("QueueUrl", queueUrl)
.when().post("/").then().statusCode(200);
}
private static String createTopic(String accountId, String topicName) {
return given().header("Authorization", authorization(accountId, "sns"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic").formParam("Name", topicName)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
}
private static void deleteTopic(String accountId, String topicArn) {
given().header("Authorization", authorization(accountId, "sns"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteTopic").formParam("TopicArn", topicArn)
.when().post("/").then().statusCode(200);
}
private ValidatableResponse putNotification(String queueArn) {
String xml = "<NotificationConfiguration><QueueConfiguration><Queue>" + queueArn
+ "</Queue><Event>s3:ObjectCreated:*</Event></QueueConfiguration></NotificationConfiguration>";
return given().header("Authorization", authorization(BUCKET_ACCOUNT, "s3"))
.contentType("application/xml").body(xml)
.when().put("/" + bucket + "?notification").then();
}
private ValidatableResponse putTopicNotification(String topicArn) {
String xml = "<NotificationConfiguration><TopicConfiguration><Topic>" + topicArn
+ "</Topic><Event>s3:ObjectCreated:*</Event></TopicConfiguration></NotificationConfiguration>";
return given().header("Authorization", authorization(BUCKET_ACCOUNT, "s3"))
.contentType("application/xml").body(xml)
.when().put("/" + bucket + "?notification").then();
}
private ValidatableResponse getNotification() {
return given().header("Authorization", authorization(BUCKET_ACCOUNT, "s3"))
.when().get("/" + bucket + "?notification").then().statusCode(200);
}
private static String queueArn(String accountId, String queueName) {
return "arn:aws:sqs:" + REGION + ":" + accountId + ":" + queueName;
}
private static String topicArn(String accountId, String topicName) {
return "arn:aws:sns:" + REGION + ":" + accountId + ":" + topicName;
}
private static String authorization(String accountId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20261001/" + REGION
+ "/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -0,0 +1,351 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@QuarkusTest
class S3NotificationDestinationValidationIntegrationTest {
private static final String REGION = "us-east-1";
private static final String OTHER_ACCOUNT = "000000000002";
@Inject SqsService sqsService;
@InjectSpy SnsService snsService;
@Inject RegionResolver regionResolver;
@Inject ObjectMapper objectMapper;
private String bucket;
private final List<String> queueUrls = new ArrayList<>();
private final List<String> topicArns = new ArrayList<>();
@BeforeEach
void createBucket() {
bucket = "notification-validation-" + UUID.randomUUID().toString().substring(0, 8);
given().when().put("/" + bucket).then().statusCode(200);
}
@AfterEach
void removeDestinations() {
given().when().delete("/" + bucket).then().statusCode(204);
for (String topicArn : topicArns) {
snsService.deleteTopic(topicArn, REGION);
}
for (String queueUrl : queueUrls) {
sqsService.deleteQueue(queueUrl, REGION);
}
}
@Test
void malformedArnIsRejectedEvenWhenDestinationValidationIsSkipped() {
String xml = notificationConfiguration(queueConfiguration("not-an-arn"));
given().contentType("application/xml").body(xml)
.when().put("/" + bucket + "?notification")
.then().statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"))
.body(containsString("<Message>The ARN could not be parsed</Message>"))
.body(containsString("<ArgumentName>Queue</ArgumentName>"))
.body(containsString("<ArgumentValue>not-an-arn</ArgumentValue>"));
given().header("x-amz-skip-destination-validation", "true")
.contentType("application/xml").body(xml)
.when().put("/" + bucket + "?notification")
.then().statusCode(400)
.body(containsString("<ArgumentName>Queue</ArgumentName>"));
given().when().get("/" + bucket + "?notification")
.then().statusCode(200).body(not(containsString("QueueConfiguration")));
}
@Test
void wrongDestinationServiceIsRejectedBeforeSkipOrExistenceChecks() {
String queueFieldWithTopicArn = regionResolver.buildArn("sns", REGION, "wrong-service");
putNotification(notificationConfiguration(queueConfiguration(queueFieldWithTopicArn)), true)
.statusCode(400)
.body(containsString("<Message>The ARN could not be parsed</Message>"))
.body(containsString("<ArgumentName>Queue</ArgumentName>"));
String topicFieldWithQueueArn = regionResolver.buildArn("sqs", REGION, "wrong-service");
putNotification(notificationConfiguration(topicConfiguration(topicFieldWithQueueArn)), true)
.statusCode(400)
.body(containsString("<ArgumentName>Topic</ArgumentName>"));
putNotification(notificationConfiguration(lambdaConfiguration("not-a-lambda-arn")), true)
.statusCode(400)
.body(containsString("<ArgumentName>CloudFunction</ArgumentName>"));
}
@Test
void missingDestinationsAreReportedTogetherWithoutReplacingPreviousConfiguration() {
String existingQueueArn = createQueue("existing", Map.of());
putNotification(notificationConfiguration(queueConfiguration(existingQueueArn)), false)
.statusCode(200);
Message initialTestEvent = receiveQueueMessage(queueUrls.getFirst()).getFirst();
sqsService.deleteMessage(queueUrls.getFirst(), initialTestEvent.getReceiptHandle(), REGION);
String missingQueueOne = regionResolver.buildArn("sqs", REGION, "missing-one");
String missingQueueTwo = regionResolver.buildArn("sqs", REGION, "missing-two");
String missingTopic = regionResolver.buildArn("sns", REGION, "missing-topic");
String missingFunction = regionResolver.buildArn("lambda", REGION, "function:missing-function");
putNotification(notificationConfiguration(
queueConfiguration(missingQueueOne) + queueConfiguration(missingQueueTwo)
+ topicConfiguration(missingTopic) + lambdaConfiguration(missingFunction)), false)
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"))
.body(containsString("Unable to validate the following destination configurations"))
.body(containsString("<ArgumentName1>" + missingQueueOne + "</ArgumentName1>"))
.body(containsString("<ArgumentValue1>The destination queue does not exist</ArgumentValue1>"))
.body(containsString("<ArgumentName2>" + missingQueueTwo + "</ArgumentName2>"))
.body(containsString("<ArgumentName3>" + missingTopic + "</ArgumentName3>"))
.body(containsString("<ArgumentName4>" + missingFunction + ", null</ArgumentName4>"))
.body(containsString("<ArgumentValue4>Not authorized to invoke function ["
+ missingFunction + "]</ArgumentValue4>"));
given().when().get("/" + bucket + "?notification")
.then().statusCode(200)
.body(containsString(existingQueueArn))
.body(not(containsString(missingQueueOne)))
.body(not(containsString(missingTopic)));
assertTrue(receiveQueueMessage(queueUrls.getFirst()).isEmpty());
}
@Test
void skipDestinationValidationStoresUnknownDestinationsWithoutSendingTestEvent() {
String existingQueueArn = createQueue("skip-existing", Map.of());
String missingQueueArn = regionResolver.buildArn("sqs", REGION, "skip-missing");
String missingTopicArn = regionResolver.buildArn("sns", REGION, "skip-topic");
String missingFunctionArn = regionResolver.buildArn("lambda", REGION, "function:skip-function");
putNotification(notificationConfiguration(queueConfiguration(existingQueueArn)
+ queueConfiguration(missingQueueArn)
+ topicConfiguration(missingTopicArn)
+ lambdaConfiguration(missingFunctionArn)), true).statusCode(200);
given().when().get("/" + bucket + "?notification")
.then().statusCode(200)
.body(containsString(existingQueueArn))
.body(containsString(missingQueueArn))
.body(containsString(missingTopicArn))
.body(containsString(missingFunctionArn));
assertTrue(receiveQueueMessage(queueUrls.getFirst()).isEmpty());
}
@Test
void validQueueAndTopicReceiveTestEventWithoutRecords() throws Exception {
String directQueueArn = createQueue("direct", Map.of());
String subscribedQueueArn = createQueue("subscribed", Map.of());
String topicArn = createTopic("test-topic");
snsService.subscribe(topicArn, "sqs", subscribedQueueArn, REGION,
Map.of("RawMessageDelivery", "true"));
putNotification(notificationConfiguration(queueConfiguration(directQueueArn)
+ topicConfiguration(topicArn)), false).statusCode(200);
assertTestEvent(receiveQueueMessage(queueUrls.get(0)).getFirst().getBody());
assertTestEvent(receiveQueueMessage(queueUrls.get(1)).getFirst().getBody());
}
@Test
void crossRegionTopicReceivesTestEventAndLaterObjectEvent() throws Exception {
String topicRegion = "ap-southeast-2";
String queueName = "notification-topic-cross-region-" + UUID.randomUUID().toString().substring(0, 8);
String queueUrl = sqsService.createQueue(queueName, Map.of(), topicRegion).getQueueUrl();
String queueArn = sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), topicRegion)
.get("QueueArn");
String topicArn = snsService.createTopic(queueName, Map.of(), Map.of(), topicRegion).getTopicArn();
try {
snsService.subscribe(topicArn, "sqs", queueArn, topicRegion,
Map.of("RawMessageDelivery", "true"));
putNotification(notificationConfiguration(topicConfiguration(topicArn)), false).statusCode(200);
Message testEvent = sqsService.receiveMessage(queueUrl, 1, 0, 0, topicRegion).getFirst();
assertTestEvent(testEvent.getBody());
sqsService.deleteMessage(queueUrl, testEvent.getReceiptHandle(), topicRegion);
given().contentType("text/plain").body("payload")
.when().put("/" + bucket + "/cross-region-object")
.then().statusCode(200);
JsonNode objectEvent = objectMapper.readTree(
sqsService.receiveMessage(queueUrl, 1, 0, 0, topicRegion).getFirst().getBody());
assertEquals("aws:s3", objectEvent.path("Records").get(0).path("eventSource").asText());
assertEquals("cross-region-object", objectEvent.path("Records").get(0)
.path("s3").path("object").path("key").asText());
} finally {
given().when().delete("/" + bucket + "/cross-region-object").then().statusCode(204);
snsService.deleteTopic(topicArn, topicRegion);
sqsService.deleteQueue(queueUrl, topicRegion);
}
}
@Test
void failedTestMessageLeavesPreviousConfigurationUntouched() {
String validQueueArn = createQueue("before-failure", Map.of());
putNotification(notificationConfiguration(queueConfiguration(validQueueArn)), false)
.statusCode(200);
String fifoQueueArn = createQueue("cannot-send.fifo", Map.of("FifoQueue", "true"));
putNotification(notificationConfiguration(queueConfiguration(fifoQueueArn)), false)
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"))
.body(containsString("<ArgumentName1>" + fifoQueueArn + "</ArgumentName1>"));
given().when().get("/" + bucket + "?notification")
.then().statusCode(200)
.body(containsString(validQueueArn))
.body(not(containsString(fifoQueueArn)));
}
@Test
void crossAccountQueueReceivesTestEventWithoutIamEnforcement() throws Exception {
String queueName = "notification-cross-account-" + UUID.randomUUID().toString().substring(0, 8);
String auth = "AWS4-HMAC-SHA256 Credential=" + OTHER_ACCOUNT
+ "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";
String queueUrl = given().header("Authorization", auth)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue").formParam("QueueName", queueName)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
String queueArn = "arn:aws:sqs:" + REGION + ":" + OTHER_ACCOUNT + ":" + queueName;
try {
putNotification(notificationConfiguration(queueConfiguration(queueArn)), false).statusCode(200);
Message testEvent = sqsService.receiveMessage(queueUrl, 1, 0, 0, REGION).getFirst();
assertTestEvent(testEvent.getBody());
sqsService.deleteMessage(queueUrl, testEvent.getReceiptHandle(), REGION);
given().contentType("text/plain").body("payload")
.when().put("/" + bucket + "/cross-account-object").then().statusCode(200);
assertTrue(sqsService.receiveMessage(queueUrl, 1, 0, 0, REGION).getFirst()
.getBody().contains("cross-account-object"));
given().when().delete("/" + bucket + "/cross-account-object").then().statusCode(204);
} finally {
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue").formParam("QueueUrl", queueUrl)
.when().post("/").then().statusCode(200);
}
}
@Test
void crossAccountTopicIsValidatedWithoutTestPublishByDefault() {
String topicName = "notification-cross-account-" + UUID.randomUUID().toString().substring(0, 8);
String authorization = "AWS4-HMAC-SHA256 Credential=" + OTHER_ACCOUNT
+ "/20261001/us-east-1/sns/aws4_request, SignedHeaders=host, Signature=abc";
String topicArn = given().header("Authorization", authorization)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic").formParam("Name", topicName)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
try {
assertTrue(snsService.topicExists(topicArn, REGION));
putNotification(notificationConfiguration(topicConfiguration(topicArn)), false).statusCode(200);
verify(snsService, never()).publish(eq(topicArn), isNull(), anyString(),
eq("Amazon S3 Notification"), eq(REGION));
given().when().get("/" + bucket + "?notification")
.then().statusCode(200).body(containsString(topicArn));
String missingArn = "arn:aws:sns:" + REGION + ":" + OTHER_ACCOUNT + ":notification-missing-"
+ UUID.randomUUID();
putNotification(notificationConfiguration(topicConfiguration(missingArn)), false)
.statusCode(400).body(containsString("The destination topic does not exist"));
given().when().get("/" + bucket + "?notification")
.then().statusCode(200).body(containsString(topicArn)).body(not(containsString(missingArn)));
String ownTopicArn = createTopic("same-account");
putNotification(notificationConfiguration(topicConfiguration(ownTopicArn)), false).statusCode(200);
verify(snsService).publish(eq(ownTopicArn), isNull(), anyString(),
eq("Amazon S3 Notification"), eq(REGION));
} finally {
given().header("Authorization", authorization).contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteTopic").formParam("TopicArn", topicArn)
.when().post("/").then().statusCode(200);
}
}
private String createQueue(String suffix, Map<String, String> attributes) {
String queueName = "notification-" + suffix + "-" + UUID.randomUUID().toString().substring(0, 8);
if (queueName.contains(".fifo-")) {
queueName = queueName.replace(".fifo-", "-") + ".fifo";
}
String queueUrl = sqsService.createQueue(queueName, attributes, REGION).getQueueUrl();
queueUrls.add(queueUrl);
return sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn");
}
private String createTopic(String suffix) {
String topicArn = snsService.createTopic(
"notification-" + suffix + "-" + UUID.randomUUID().toString().substring(0, 8),
Map.of(), Map.of(), REGION).getTopicArn();
topicArns.add(topicArn);
return topicArn;
}
private List<Message> receiveQueueMessage(String queueUrl) {
return sqsService.receiveMessage(queueUrl, 1, 0, 0, REGION);
}
private void assertTestEvent(String json) throws Exception {
JsonNode event = objectMapper.readTree(json);
assertEquals("Amazon S3", event.path("Service").asText());
assertEquals("s3:TestEvent", event.path("Event").asText());
assertEquals(bucket, event.path("Bucket").asText());
assertNotNull(Instant.parse(event.path("Time").asText()));
assertFalse(event.path("RequestId").asText().isBlank());
assertFalse(event.path("HostId").asText().isBlank());
assertFalse(event.has("Records"));
}
private ValidatableResponse putNotification(String xml, boolean skip) {
return given().header("x-amz-skip-destination-validation", Boolean.toString(skip))
.contentType("application/xml").body(xml)
.when().put("/" + bucket + "?notification")
.then();
}
private static String notificationConfiguration(String contents) {
return "<NotificationConfiguration>" + contents + "</NotificationConfiguration>";
}
private static String queueConfiguration(String arn) {
return "<QueueConfiguration><Queue>" + arn
+ "</Queue><Event>s3:ObjectCreated:*</Event></QueueConfiguration>";
}
private static String topicConfiguration(String arn) {
return "<TopicConfiguration><Topic>" + arn
+ "</Topic><Event>s3:ObjectCreated:*</Event></TopicConfiguration>";
}
private static String lambdaConfiguration(String arn) {
return "<CloudFunctionConfiguration><CloudFunction>" + arn
+ "</CloudFunction><Event>s3:ObjectCreated:*</Event></CloudFunctionConfiguration>";
}
}
@@ -108,6 +108,10 @@ class S3PresignedPostIntegrationTest {
.then()
.statusCode(200);
consumeValidationEvent(postQueueUrl);
consumeValidationEvent(putQueueUrl);
consumeValidationEvent(wildcardQueueUrl);
given()
.multiPart("key", "uploads/notified.txt")
.multiPart("file", "notified.txt", "notified".getBytes(StandardCharsets.UTF_8), "text/plain")
@@ -169,6 +173,34 @@ class S3PresignedPostIntegrationTest {
containsString("\"eventName\":\"ObjectCreated:Post\""));
}
private void consumeValidationEvent(String queueUrl) {
String receiptHandle = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.when()
.post("/")
.then()
.statusCode(200)
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body",
containsString("\"Event\":\"s3:TestEvent\""))
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body",
containsString("\"Bucket\":\"" + BUCKET + "\""))
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body", not(containsString("\"Records\"")))
.extract().xmlPath().getString("ReceiveMessageResponse.ReceiveMessageResult.Message.ReceiptHandle");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteMessage")
.formParam("QueueUrl", queueUrl)
.formParam("ReceiptHandle", receiptHandle)
.when()
.post("/")
.then()
.statusCode(200);
}
private void deleteQueue(String queueUrl) {
given()
.contentType("application/x-www-form-urlencoded")
@@ -5,7 +5,9 @@ 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.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.s3.model.ChecksumType;
import io.github.hectorvent.floci.services.s3.model.FilterRule;
import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesResult;
@@ -34,6 +36,8 @@ import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class S3ServiceTest {
@@ -594,7 +598,7 @@ class S3ServiceTest {
S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir.resolve("notif-s3"),
false, lambdaInvoker, regionResolver);
service.createBucket("test-bucket", "ap-northeast-1");
service.putBucketNotificationConfiguration("test-bucket", lambdaNotificationConfig("uploads/", ".json"));
service.putBucketNotificationConfiguration("test-bucket", lambdaNotificationConfig("uploads/", ".json"), true);
service.putObject("test-bucket", "uploads/test.json", "{\"ok\":true}".getBytes(StandardCharsets.UTF_8),
"application/json", null);
@@ -613,7 +617,7 @@ class S3ServiceTest {
S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir.resolve("notif-s3-no-match"),
false, lambdaInvoker, regionResolver);
service.createBucket("test-bucket", "ap-northeast-1");
service.putBucketNotificationConfiguration("test-bucket", lambdaNotificationConfig("uploads/", ".json"));
service.putBucketNotificationConfiguration("test-bucket", lambdaNotificationConfig("uploads/", ".json"), true);
service.putObject("test-bucket", "incoming/test.txt", "ignored".getBytes(StandardCharsets.UTF_8),
"text/plain", null);
@@ -635,13 +639,90 @@ class S3ServiceTest {
"arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test:PROD",
List.of("s3:ObjectCreated:Put"),
List.of()));
service.putBucketNotificationConfiguration("test-bucket", config);
service.putBucketNotificationConfiguration("test-bucket", config, true);
service.putObject("test-bucket", "a.json", "{}".getBytes(StandardCharsets.UTF_8), "application/json", null);
assertEquals("s3-notif-test:PROD", lambdaInvoker.functionName);
}
@Test
void foreignLambdaArnDoesNotResolveToSameNamedLocalFunction() {
LambdaService lambdaService = mock(LambdaService.class);
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
String localArn = "arn:aws:lambda:us-east-1:000000000000:function:shared-name";
String foreignArn = "arn:aws:lambda:us-east-1:111111111111:function:shared-name";
LambdaFunction localFunction = new LambdaFunction();
localFunction.setFunctionArn(localArn);
when(lambdaService.getFunction("us-east-1", localArn, null)).thenReturn(localFunction);
when(lambdaService.getFunction("us-east-1", foreignArn, null)).thenReturn(localFunction);
S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("lambda-account-validation"), false, lambdaService, regionResolver);
service.createBucket("test-bucket", "us-east-1");
NotificationConfiguration local = new NotificationConfiguration();
local.getLambdaFunctionConfigurations().add(new LambdaNotification(
"local", localArn, List.of("s3:ObjectCreated:*"), List.of()));
service.putBucketNotificationConfiguration("test-bucket", local);
NotificationConfiguration foreign = new NotificationConfiguration();
foreign.getLambdaFunctionConfigurations().add(new LambdaNotification(
"foreign", foreignArn, List.of("s3:ObjectCreated:*"), List.of()));
AwsException error = assertThrows(AwsException.class,
() -> service.putBucketNotificationConfiguration("test-bucket", foreign));
assertEquals("InvalidArgument", error.getErrorCode());
assertEquals(foreignArn + ", null", error.getExtendedData().get("ArgumentName1"));
assertEquals(localArn, service.getBucketNotificationConfiguration("test-bucket")
.getLambdaFunctionConfigurations().getFirst().functionArn());
}
@Test
void notificationValidationCannotRestoreADeletedBucket() {
LambdaService lambdaService = mock(LambdaService.class);
RegionResolver regionResolver = new RegionResolver("ap-northeast-1", "000000000000");
String arn = "arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test";
LambdaFunction function = new LambdaFunction();
function.setFunctionArn(arn);
S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("notification-deleted-bucket"), false, lambdaService, regionResolver);
service.createBucket("test-bucket", "ap-northeast-1");
when(lambdaService.getFunction("ap-northeast-1", arn, null)).thenAnswer(ignored -> {
service.deleteBucket("test-bucket");
return function;
});
AwsException error = assertThrows(AwsException.class,
() -> service.putBucketNotificationConfiguration("test-bucket",
lambdaNotificationConfig("", "")));
assertEquals("NoSuchBucket", error.getErrorCode());
assertEquals("NoSuchBucket", assertThrows(AwsException.class,
() -> service.getBucketNotificationConfiguration("test-bucket")).getErrorCode());
}
@Test
void notificationValidationCannotOverwriteARecreatedBucket() {
LambdaService lambdaService = mock(LambdaService.class);
RegionResolver regionResolver = new RegionResolver("ap-northeast-1", "000000000000");
String arn = "arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test";
LambdaFunction function = new LambdaFunction();
function.setFunctionArn(arn);
S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("notification-recreated-bucket"), false, lambdaService, regionResolver);
service.createBucket("test-bucket", "ap-northeast-1");
when(lambdaService.getFunction("ap-northeast-1", arn, null)).thenAnswer(ignored -> {
service.deleteBucket("test-bucket");
service.createBucket("test-bucket", "ap-northeast-1");
return function;
});
AwsException error = assertThrows(AwsException.class,
() -> service.putBucketNotificationConfiguration("test-bucket",
lambdaNotificationConfig("", "")));
assertEquals("NoSuchBucket", error.getErrorCode());
assertTrue(service.getBucketNotificationConfiguration("test-bucket")
.getLambdaFunctionConfigurations().isEmpty());
}
@Test
void deleteObjectVersionFiresObjectRemovedDeleteWithTheDeletedVersionId() throws IOException {
RecordingLambdaInvoker lambdaInvoker = new RecordingLambdaInvoker();
@@ -694,7 +775,7 @@ class S3ServiceTest {
"arn:aws:lambda:us-east-1:000000000000:function:s3-notif-test",
List.of("s3:ObjectRemoved:*"),
List.of()));
service.putBucketNotificationConfiguration("test-bucket", config);
service.putBucketNotificationConfiguration("test-bucket", config, true);
return service;
}
@@ -436,6 +436,28 @@ class S3VersioningIntegrationTest {
.then()
.statusCode(200);
String validationReceipt = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.when()
.post("/")
.then()
.statusCode(200)
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body",
containsString("\"Event\":\"s3:TestEvent\""))
.extract().xmlPath().getString("ReceiveMessageResponse.ReceiveMessageResult.Message.ReceiptHandle");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteMessage")
.formParam("QueueUrl", queueUrl)
.formParam("ReceiptHandle", validationReceipt)
.when()
.post("/")
.then()
.statusCode(200);
String olderVersionId = given()
.body("v1")
.contentType("text/plain")
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
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.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
@@ -793,6 +794,42 @@ class SnsServiceTest {
"arn:aws:sns:us-east-1:000000000000:ghost-topic", REGION));
}
@ParameterizedTest
@ValueSource(strings = {ACCOUNT, "000000000002"})
void topicExists_migratesLegacyTopicToArnAccount(String accountId) {
String arn = "arn:aws:sns:us-east-1:" + accountId + ":legacy-topic";
String key = "topic::" + REGION + "::" + arn;
Topic topic = new Topic("legacy-topic", arn);
InMemoryStorage<String, Topic> raw = new InMemoryStorage<>();
raw.put(key, topic);
AccountAwareStorageBackend<Topic> store = new AccountAwareStorageBackend<>(raw, null, ACCOUNT);
SnsService service = new SnsService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), null, null);
assertTrue(service.topicExists(arn, REGION));
assertEquals(topic, raw.get(accountId + "/" + key).orElseThrow());
assertTrue(raw.get(key).isEmpty());
if (!ACCOUNT.equals(accountId)) {
assertTrue(raw.get(ACCOUNT + "/" + key).isEmpty());
}
}
@Test
void topicExists_doesNotClaimLegacyTopicWithDifferentArn() {
String arn = "arn:aws:sns:us-east-1:000000000002:legacy-topic";
String key = "topic::" + REGION + "::" + arn;
Topic otherTopic = new Topic("legacy-topic", "arn:aws:sns:us-east-1:000000000003:legacy-topic");
InMemoryStorage<String, Topic> raw = new InMemoryStorage<>();
raw.put(key, otherTopic);
AccountAwareStorageBackend<Topic> store = new AccountAwareStorageBackend<>(raw, null, ACCOUNT);
SnsService service = new SnsService(store, new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), null, null);
assertFalse(service.topicExists(arn, REGION));
assertEquals(otherTopic, raw.get(key).orElseThrow());
assertTrue(raw.get("000000000002/" + key).isEmpty());
}
private static Map<String, MessageAttributeValue> attr(String name, String value, String dataType) {
return Map.of(name, new MessageAttributeValue(value, dataType));
}