fix(s3,sns): preserve root service-host routing (#1625)

* fix(s3): preserve ListBuckets on S3 service hosts

- Treat bare s3.* service endpoint hosts as bucketless S3 requests

- Keep virtual-hosted bucket parsing for bucket.s3.* and bucket.localhost forms

- Add parser and integration coverage for LocalStack and Floci S3 service host domains

* fix(sns): route SubscribeURL confirmations to SNS

- Route SNS ConfirmSubscription GET requests on / through the SNS query handler before normal S3 root handling
- Preserve S3 ListBuckets behavior for non-SNS root GET requests
- Add SNS HTTP delivery regressions for inline 200 confirmation and SubscribeURL GET confirmation

* test(sns): fix race in inline-confirm HTTP delivery test

The confirming-webhook handler recorded the received request before running
confirmSubscription(), so awaitRequests() unblocked and the test published
before the subscription was actually confirmed, delivering 0 notifications
under load (flaky on CI). Record the request only after confirmSubscription()
completes, making awaitRequests() a real barrier. Log the confirmation failure
instead of swallowing it so a genuine failure is diagnosable.

* fix(sns): route UnsubscribeURL confirmations to SNS

UnsubscribeURL is emitted as a plain GET link against the service root,
the same endpoint collision with S3 ListBuckets that SubscribeURL had.
Extend the root-GET delegation to forward Action=Unsubscribe to the SNS
query handler alongside ConfirmSubscription, closing the whole class of
gap rather than a single action.

These links are unsigned, so the region cannot come from the request auth
header. Derive it from the region-bearing ARN the link carries
(SubscriptionArn for Unsubscribe, TopicArn for ConfirmSubscription), so a
subscription in a non-default region resolves instead of returning NotFound.

- Delegate Unsubscribe GETs on / to SnsQueryHandler in S3Controller
- Recover the SNS region from the link ARN via AwsArnUtils.regionOrDefault
- Add a regression in us-west-2: the UnsubscribeURL GET reaches SNS
  (UnsubscribeResponse, not ListBuckets) and the subscription is removed
This commit is contained in:
TiM authored and GitHub committed 2026-07-02 23:44:14 -05:00
1 parent 345e83c34d
commit 2a36522094
5 files changed
+295 -1

No files matched your search

@@ -65,6 +65,13 @@ class S3VirtualHostFilterTest {
"localhost:4566, localhost",
"localhost, localhost",
"plain-host, plain-host",
// Bare S3 service hosts must NOT be treated as a bucket named s3
"s3.localhost:4566, localhost",
"s3.localhost, localhost",
"s3.localhost.localstack.cloud, localhost",
"s3.localhost.localstack.cloud:4566, localhost",
"s3.localhost.floci.io, localhost",
"s3.localhost.floci.io:4566, localhost",
// K8s service hostname used as endpoint (path-style) — must NOT be rewritten
"floci.default.svc.cluster.local, localhost",
"floci-service.namespace.svc.cluster.local, localhost",
@@ -247,6 +247,32 @@ class S3VirtualHostIntegrationTest {
.body(equalTo("region-qualified content"));
}
@Test
@Order(17)
void listBucketsViaLocalStackS3ServiceHost() {
given()
.header("Host", "s3.localhost.localstack.cloud")
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("ListAllMyBucketsResult"))
.body(containsString(BUCKET));
}
@Test
@Order(18)
void listBucketsViaFlociS3ServiceHost() {
given()
.header("Host", "s3.localhost.floci.io")
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("ListAllMyBucketsResult"))
.body(containsString(BUCKET));
}
@Test
@Order(20)
void cleanupAndDeleteBucket() {
@@ -18,6 +18,7 @@ import java.util.Map;
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.*;
/**
@@ -31,6 +32,8 @@ class SnsHttpDeliveryIntegrationTest {
private static int httpPort;
private static final List<ReceivedRequest> receivedRequests = new CopyOnWriteArrayList<>();
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final java.util.logging.Logger LOG =
java.util.logging.Logger.getLogger(SnsHttpDeliveryIntegrationTest.class.getName());
record ReceivedRequest(String body, Map<String, List<String>> headers) {}
@BeforeAll
@@ -45,6 +48,32 @@ class SnsHttpDeliveryIntegrationTest {
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
httpServer.createContext("/confirming-webhook", exchange -> {
byte[] bodyBytes = exchange.getRequestBody().readAllBytes();
String body = new String(bodyBytes, StandardCharsets.UTF_8);
Map<String, List<String>> headers = exchange.getRequestHeaders();
ReceivedRequest received = new ReceivedRequest(body, headers);
try {
// Confirm the subscription BEFORE recording the request, so a test that
// awaits this request observes it only once the subscription is actually
// confirmed. Recording first would let a subsequent publish race ahead of
// the confirmation and see a still-pending subscription (flaky delivery).
if ("SubscriptionConfirmation".equals(firstHeader(headers, "X-amz-sns-message-type"))) {
confirmSubscription(received);
}
receivedRequests.add(received);
exchange.sendResponseHeaders(200, 0);
} catch (Exception e) {
// Record even on failure so awaitRequests unblocks and the assertion
// reports the real state instead of timing out opaquely.
receivedRequests.add(received);
LOG.log(java.util.logging.Level.SEVERE,
"confirming-webhook: subscription confirmation failed", e);
exchange.sendResponseHeaders(500, 0);
} finally {
exchange.close();
}
});
httpServer.start();
}
@@ -65,6 +94,11 @@ class SnsHttpDeliveryIntegrationTest {
}
}
private static String firstHeader(Map<String, List<String>> headers, String name) {
List<String> values = headers.get(name);
return values == null || values.isEmpty() ? null : values.get(0);
}
/**
* Extracts the Token and TopicArn from the SubscriptionConfirmation message
* and calls ConfirmSubscription via POST (matching how the SDK confirms).
@@ -178,6 +212,194 @@ class SnsHttpDeliveryIntegrationTest {
assertEquals("production", msgAttrs.get("env").get("Value").asText());
}
@Test
void publish_toHttpSubscriber_confirmedDuringSuccessfulHandshake_deliversNotification() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/confirming-webhook";
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-inline-confirm-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
awaitRequests(1);
assertEquals(1, receivedRequests.size());
assertEquals("SubscriptionConfirmation", firstHeader(receivedRequests.get(0).headers(), "X-amz-sns-message-type"));
receivedRequests.clear();
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "delivered after inline confirm")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
awaitRequests(1);
assertEquals(1, receivedRequests.size());
ReceivedRequest req = receivedRequests.get(0);
assertEquals("Notification", firstHeader(req.headers(), "X-amz-sns-message-type"));
JsonNode envelope = objectMapper.readTree(req.body());
assertEquals("Notification", envelope.get("Type").asText());
assertEquals("delivered after inline confirm", envelope.get("Message").asText());
}
@Test
void subscribeUrl_getConfirmsSubscriptionAndAllowsDelivery() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/webhook";
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-subscribe-url-get-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
awaitRequests(1);
assertEquals(1, receivedRequests.size());
JsonNode confirmation = objectMapper.readTree(receivedRequests.get(0).body());
given()
.queryParam("Action", "ConfirmSubscription")
.queryParam("TopicArn", confirmation.get("TopicArn").asText())
.queryParam("Token", confirmation.get("Token").asText())
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
receivedRequests.clear();
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "delivered after SubscribeURL GET")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
awaitRequests(1);
assertEquals(1, receivedRequests.size());
assertEquals("Notification", firstHeader(receivedRequests.get(0).headers(), "X-amz-sns-message-type"));
}
@Test
void unsubscribeUrl_getRoutesToSnsAndRemovesSubscription() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/webhook";
// Pin the subscription to a non-default region. The SubscribeURL/UnsubscribeURL
// links SNS emits are unsigned, so the delegation must recover this region from
// the ARN in the link, not from the (absent) request auth.
String snsAuth = "AWS4-HMAC-SHA256 Credential=000000000000/20260101/us-west-2/sns/aws4_request";
String topicArn = given()
.header("Authorization", snsAuth)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-unsubscribe-url-get-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
assertTrue(topicArn.contains(":us-west-2:"), "topic should live in us-west-2");
given()
.header("Authorization", snsAuth)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
awaitRequests(1);
assertEquals(1, receivedRequests.size());
JsonNode confirmation = objectMapper.readTree(receivedRequests.get(0).body());
// Confirm via the SubscribeURL GET (unsigned) to obtain a real SubscriptionArn.
// Region is recovered from the TopicArn, so the pending sub in us-west-2 is found.
String subscriptionArn = given()
.queryParam("Action", "ConfirmSubscription")
.queryParam("TopicArn", confirmation.get("TopicArn").asText())
.queryParam("Token", confirmation.get("Token").asText())
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"))
.extract().xmlPath().getString("ConfirmSubscriptionResponse.ConfirmSubscriptionResult.SubscriptionArn");
// Following the UnsubscribeURL is a plain GET on the service root. It must
// reach SNS (UnsubscribeResponse), not fall through to S3 ListBuckets, and
// its region must come from the SubscriptionArn (us-west-2), not the default.
given()
.queryParam("Action", "Unsubscribe")
.queryParam("SubscriptionArn", subscriptionArn)
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("UnsubscribeResponse"))
.body(not(containsString("ListAllMyBucketsResult")));
// The unsubscribe took effect: the subscription is no longer listed.
given()
.header("Authorization", snsAuth)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListSubscriptionsByTopic")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString(subscriptionArn)));
}
@Test
void publish_toHttpSubscriber_rawMessageDelivery() throws Exception {
receivedRequests.clear();