Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(s3): Evaluate S3 CORS against incoming HTTP Requests (#131)

Julian Brudere78c8337948c
diff --git a/.gitignore b/.gitignore
index 8583daf254..2880bbd1c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,6 +9,7 @@ data/
.project
.classpath
.vscode/
+.zed/settings.json
.DS_Store
.zed/settings.json
@@ -18,4 +19,4 @@ COPILOT.md
.claude
posts
-local
\ No newline at end of file
+local
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
index 6ac38f740c..c86e4d31ae 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
@@ -37,6 +37,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Arrays;
+import java.util.Optional;
import java.util.Set;
import org.jboss.logging.Logger;
@@ -537,6 +539,78 @@ public class S3Controller {
}
}
+ // --- CORS preflight ---
+
+ @OPTIONS
+ @Path("/{bucket}")
+ public Response handleOptionsBucket(@PathParam("bucket") String bucket,
+ @HeaderParam("Origin") String origin,
+ @HeaderParam("Access-Control-Request-Method") String requestMethod,
+ @HeaderParam("Access-Control-Request-Headers") String requestHeadersStr) {
+ return handleCorsPreFlight(bucket, origin, requestMethod, requestHeadersStr);
+ }
+
+ @OPTIONS
+ @Path("/{bucket}/{key:.+}")
+ public Response handleOptionsObject(@PathParam("bucket") String bucket,
+ @PathParam("key") String key,
+ @HeaderParam("Origin") String origin,
+ @HeaderParam("Access-Control-Request-Method") String requestMethod,
+ @HeaderParam("Access-Control-Request-Headers") String requestHeadersStr) {
+ return handleCorsPreFlight(bucket, origin, requestMethod, requestHeadersStr);
+ }
+
+ private Response handleCorsPreFlight(String bucket, String origin,
+ String requestMethod, String requestHeadersStr) {
+ if (origin == null || origin.isBlank()
+ || requestMethod == null || requestMethod.isBlank()) {
+ // Not a valid CORS preflight — return a plain 200 with no CORS headers
+ return Response.ok().build();
+ }
+ List<String> requestHeaders = (requestHeadersStr != null && !requestHeadersStr.isBlank())
+ ? Arrays.stream(requestHeadersStr.split(","))
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .collect(java.util.stream.Collectors.toList())
+ : List.of();
+
+ Optional<S3Service.CorsEvalResult> evalResult =
+ s3Service.evaluateCors(bucket, origin, requestMethod, requestHeaders);
+
+ if (evalResult.isEmpty()) {
+ String body = new XmlBuilder()
+ .raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
+ .start("Error")
+ .elem("Code", "CORSResponse")
+ .elem("Message", "This CORS request is not allowed.")
+ .end("Error")
+ .build();
+ return Response.status(403)
+ .entity(body)
+ .type(MediaType.APPLICATION_XML)
+ .build();
+ }
+
+ S3Service.CorsEvalResult cors = evalResult.get();
+ var builder = Response.ok()
+ .header("Access-Control-Allow-Origin", cors.allowedOrigin())
+ .header("Access-Control-Allow-Methods", String.join(", ", cors.allowedMethods()));
+
+ if (cors.maxAgeSeconds() > 0) {
+ builder.header("Access-Control-Max-Age", cors.maxAgeSeconds());
+ }
+ if (!cors.allowedHeaders().isEmpty()) {
+ String hdrs = cors.allowedHeaders().contains("*")
+ ? "*"
+ : String.join(", ", cors.allowedHeaders());
+ builder.header("Access-Control-Allow-Headers", hdrs);
+ }
+ if (!cors.exposeHeaders().isEmpty()) {
+ builder.header("Access-Control-Expose-Headers", String.join(", ", cors.exposeHeaders()));
+ }
+ return builder.build();
+ }
+
@DELETE
@Path("/{bucket}/{key:.+}")
public Response deleteObject(@PathParam("bucket") String bucket,
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3CorsFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3CorsFilter.java
new file mode 100644
index 0000000000..8e80b76dab
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3CorsFilter.java
@@ -0,0 +1,79 @@
+package io.github.hectorvent.floci.services.s3;
+
+import jakarta.inject.Inject;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.container.ContainerResponseFilter;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.Provider;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Adds CORS response headers to actual (non-preflight) S3 requests when the
+ * request carries an {@code Origin} header and a matching CORS rule exists for
+ * the target bucket.
+ *
+ * <p>Preflight ({@code OPTIONS}) requests are handled directly by the dedicated
+ * endpoint methods in {@link S3Controller} and are intentionally skipped here.
+ */
+@Provider
+public class S3CorsFilter implements ContainerResponseFilter {
+
+ @Inject
+ S3Service s3Service;
+
+ @Override
+ public void filter(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) {
+
+ // Only handle actual requests — preflights are processed by the OPTIONS endpoints
+ if ("OPTIONS".equalsIgnoreCase(requestContext.getMethod())) return;
+
+ String origin = requestContext.getHeaderString("Origin");
+ if (origin == null || origin.isBlank()) return;
+
+ String bucket = extractBucket(requestContext.getUriInfo().getPath());
+ if (bucket == null) return;
+
+ Optional<S3Service.CorsEvalResult> evalResult =
+ s3Service.evaluateCors(bucket, origin, requestContext.getMethod(), List.of());
+ if (evalResult.isEmpty()) return;
+
+ S3Service.CorsEvalResult cors = evalResult.get();
+ MultivaluedMap<String, Object> headers = responseContext.getHeaders();
+
+ // putSingle replaces any value already set by a resource method or earlier filter,
+ // preventing duplicate Access-Control-Allow-Origin / Expose-Headers entries.
+ headers.putSingle("Access-Control-Allow-Origin", cors.allowedOrigin());
+
+ // Merge "Origin" into Vary without duplicating it; Vary may already carry other
+ // tokens (e.g. "Accept-Encoding") added by the JAX-RS runtime or other filters.
+ boolean varyHasOrigin = Optional.ofNullable(headers.get("Vary"))
+ .orElse(List.of())
+ .stream()
+ .anyMatch(v -> Arrays.stream(v.toString().split(","))
+ .map(String::trim)
+ .anyMatch("Origin"::equalsIgnoreCase));
+ if (!varyHasOrigin) {
+ headers.add("Vary", "Origin");
+ }
+
+ if (!cors.exposeHeaders().isEmpty()) {
+ headers.putSingle("Access-Control-Expose-Headers", String.join(", ", cors.exposeHeaders()));
+ }
+ }
+
+ /**
+ * Extracts the bucket name from a JAX-RS request path such as
+ * {@code /my-bucket} or {@code /my-bucket/some/key.txt}.
+ */
+ private static String extractBucket(String path) {
+ if (path == null || path.isEmpty()) return null;
+ String p = path.startsWith("/") ? path.substring(1) : path;
+ int slash = p.indexOf('/');
+ String bucket = slash > 0 ? p.substring(0, slash) : p;
+ return bucket.isEmpty() ? null : bucket;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index dd47e55d03..c5086107cb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.XmlBuilder;
+import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.s3.model.*;
@@ -1014,6 +1015,96 @@ public class S3Service {
return bucket.getCorsConfiguration();
}
+ public record CorsEvalResult(
+ String allowedOrigin,
+ List<String> allowedMethods,
+ List<String> allowedHeaders,
+ List<String> exposeHeaders,
+ int maxAgeSeconds
+ ) {}
+
+ /**
+ * Evaluates a CORS request (preflight or actual) against the bucket's CORS configuration.
+ *
+ * @param bucketName the bucket to check
+ * @param origin the Origin header value from the browser request
+ * @param requestMethod the Access-Control-Request-Method (for preflight) or the HTTP method (for actual requests)
+ * @param requestHeaders the Access-Control-Request-Headers values (may be empty for actual requests)
+ * @return the matching CORS rule details, or empty if no rule matches
+ */
+ public Optional<CorsEvalResult> evaluateCors(String bucketName, String origin,
+ String requestMethod, List<String> requestHeaders) {
+ Bucket bucket = bucketStore.get(bucketName).orElse(null);
+ if (bucket == null || bucket.getCorsConfiguration() == null) return Optional.empty();
+
+ String corsXml = bucket.getCorsConfiguration();
+ List<Map<String, List<String>>> rules = XmlParser.extractGroupsMulti(corsXml, "CORSRule");
+
+ for (Map<String, List<String>> rule : rules) {
+ List<String> allowedOrigins = rule.getOrDefault("AllowedOrigin", List.of());
+ List<String> allowedMethods = rule.getOrDefault("AllowedMethod", List.of());
+ List<String> allowedHeaders = rule.getOrDefault("AllowedHeader", List.of());
+ List<String> exposeHeaders = rule.getOrDefault("ExposeHeader", List.of());
+ List<String> maxAgeList = rule.getOrDefault("MaxAgeSeconds", List.of());
+ int maxAge = 0;
+ if (!maxAgeList.isEmpty()) {
+ String maxAgeRaw = maxAgeList.get(0);
+ if (maxAgeRaw != null) {
+ String trimmed = maxAgeRaw.trim();
+ if (!trimmed.isEmpty()) {
+ try {
+ maxAge = Integer.parseInt(trimmed);
+ } catch (NumberFormatException ignored) {
+ // Treat invalid MaxAgeSeconds as no max-age (equivalent to 0)
+ }
+ }
+ }
+ }
+
+ boolean originMatches = allowedOrigins.contains("*")
+ || (origin != null && allowedOrigins.stream().anyMatch(ao -> matchesCorsOrigin(ao, origin)));
+ if (!originMatches) continue;
+
+ if (requestMethod != null
+ && allowedMethods.stream().noneMatch(m -> m.equalsIgnoreCase(requestMethod))) continue;
+
+ if (requestHeaders != null && !requestHeaders.isEmpty()) {
+ boolean headersOk = allowedHeaders.contains("*")
+ || requestHeaders.stream().allMatch(rh ->
+ allowedHeaders.stream().anyMatch(ah -> ah.equalsIgnoreCase(rh)));
+ if (!headersOk) continue;
+ }
+
+ String echoOrigin = allowedOrigins.contains("*") ? "*" : origin;
+ return Optional.of(new CorsEvalResult(echoOrigin, allowedMethods, allowedHeaders, exposeHeaders, maxAge));
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Matches an AllowedOrigin pattern against a concrete Origin header value.
+ *
+ * <p>AWS S3 CORS allows at most one {@code *} wildcard anywhere in the pattern
+ * (e.g. {@code *}, {@code http://*.example.com}, {@code http://app-*.example.com}).
+ * The {@code *} matches zero or more characters at that position in the origin string.
+ * The concrete Origin is always treated as an exact scheme+host+port string.
+ */
+ private static boolean matchesCorsOrigin(String pattern, String origin) {
+ if ("*".equals(pattern)) return true;
+ int star = pattern.indexOf('*');
+ if (star < 0) {
+ return pattern.equals(origin);
+ }
+ // Single wildcard: split into prefix and suffix around the '*'
+ String prefix = pattern.substring(0, star);
+ String suffix = pattern.substring(star + 1);
+ // The wildcard may match zero or more characters, so the origin must be at
+ // least as long as prefix+suffix combined (no overlap allowed).
+ return origin.length() >= prefix.length() + suffix.length()
+ && origin.startsWith(prefix)
+ && origin.endsWith(suffix);
+ }
+
public void putBucketCors(String bucketName, String cors) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3CorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3CorsIntegrationTest.java
new file mode 100644
index 0000000000..a7c24baa50
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3CorsIntegrationTest.java
@@ -0,0 +1,641 @@
+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.*;
+
+/**
+ * Integration tests for S3 CORS enforcement.
+ *
+ * <p>Covers:
+ * <ul>
+ * <li>OPTIONS preflight with no CORS config → 403</li>
+ * <li>Wildcard-origin CORS config: correct preflight headers returned</li>
+ * <li>Actual request with {@code Origin} header receives {@code Access-Control-*} response headers</li>
+ * <li>Specific-origin CORS config: matching and non-matching origin / method / requested-headers</li>
+ * <li>After {@code DeleteBucketCors}, preflights return 403 again</li>
+ * <li>OPTIONS without {@code Origin} header is not a preflight (plain 200, no CORS headers)</li>
+ * </ul>
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class S3CorsIntegrationTest {
+
+ private static final String BUCKET = "cors-test-bucket";
+
+ /** AllowedOrigin=*, all common methods, wildcard headers, ExposeHeader=ETag, MaxAgeSeconds=3000 */
+ private static final String WILDCARD_CORS_XML =
+ "<CORSConfiguration>" +
+ " <CORSRule>" +
+ " <AllowedOrigin>*</AllowedOrigin>" +
+ " <AllowedMethod>GET</AllowedMethod>" +
+ " <AllowedMethod>PUT</AllowedMethod>" +
+ " <AllowedMethod>POST</AllowedMethod>" +
+ " <AllowedMethod>DELETE</AllowedMethod>" +
+ " <AllowedMethod>HEAD</AllowedMethod>" +
+ " <AllowedHeader>*</AllowedHeader>" +
+ " <ExposeHeader>ETag</ExposeHeader>" +
+ " <MaxAgeSeconds>3000</MaxAgeSeconds>" +
+ " </CORSRule>" +
+ "</CORSConfiguration>";
+
+ /** AllowedOrigin=https://example.com, GET+PUT only, specific allowed headers, two ExposeHeaders */
+ private static final String SPECIFIC_ORIGIN_CORS_XML =
+ "<CORSConfiguration>" +
+ " <CORSRule>" +
+ " <AllowedOrigin>https://example.com</AllowedOrigin>" +
+ " <AllowedMethod>GET</AllowedMethod>" +
+ " <AllowedMethod>PUT</AllowedMethod>" +
+ " <AllowedHeader>Content-Type</AllowedHeader>" +
+ " <AllowedHeader>Authorization</AllowedHeader>" +
+ " <ExposeHeader>ETag</ExposeHeader>" +
+ " <ExposeHeader>x-amz-request-id</ExposeHeader>" +
+ " <MaxAgeSeconds>600</MaxAgeSeconds>" +
+ " </CORSRule>" +
+ "</CORSConfiguration>";
+
+ /**
+ * Subdomain wildcard: http://*.example.com — covers http://foo.example.com,
+ * http://app.example.com, etc., but NOT https://foo.example.com.
+ */
+ private static final String SUBDOMAIN_WILDCARD_CORS_XML =
+ "<CORSConfiguration>" +
+ " <CORSRule>" +
+ " <AllowedOrigin>http://*.example.com</AllowedOrigin>" +
+ " <AllowedMethod>GET</AllowedMethod>" +
+ " <AllowedMethod>PUT</AllowedMethod>" +
+ " <AllowedHeader>*</AllowedHeader>" +
+ " <ExposeHeader>ETag</ExposeHeader>" +
+ " <MaxAgeSeconds>120</MaxAgeSeconds>" +
+ " </CORSRule>" +
+ "</CORSConfiguration>";
+
+ /**
+ * Mid-string wildcard: http://app-*.example.com — covers http://app-v1.example.com,
+ * http://app-staging.example.com, etc.
+ */
+ private static final String MID_WILDCARD_CORS_XML =
+ "<CORSConfiguration>" +
+ " <CORSRule>" +
+ " <AllowedOrigin>http://app-*.example.com</AllowedOrigin>" +
+ " <AllowedMethod>GET</AllowedMethod>" +
+ " <AllowedHeader>*</AllowedHeader>" +
+ " <MaxAgeSeconds>60</MaxAgeSeconds>" +
+ " </CORSRule>" +
+ "</CORSConfiguration>";
+
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void createBucket() {
+ given()
+ .when()
+ .put("/" + BUCKET)
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(99)
+ void cleanupDeleteBucket() {
+ // Remove objects created during the test first
+ given().delete("/" + BUCKET + "/hello.txt");
+
+ given()
+ .when()
+ .delete("/" + BUCKET)
+ .then()
+ .statusCode(204);
+ }
+
+ // ── No CORS config present ────────────────────────────────────────────────
+
+ @Test
+ @Order(2)
+ void optionsPreflightWithoutCorsConfigOnObjectPathReturnsForbidden() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/any-key")
+ .then()
+ .statusCode(403)
+ .body(containsString("CORSResponse"));
+ }
+
+ @Test
+ @Order(3)
+ void optionsPreflightWithoutCorsConfigOnBucketPathReturnsForbidden() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "PUT")
+ .when()
+ .options("/" + BUCKET)
+ .then()
+ .statusCode(403);
+ }
+
+ // ── Wildcard-origin CORS config ───────────────────────────────────────────
+
+ @Test
+ @Order(10)
+ void putCorsConfigWithWildcardOrigin() {
+ given()
+ .contentType("application/xml")
+ .body(WILDCARD_CORS_XML)
+ .when()
+ .put("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(11)
+ void optionsPreflightWildcardOriginReturnsOkWithAllowOriginStar() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "PUT")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("*"));
+ }
+
+ @Test
+ @Order(12)
+ void optionsPreflightReturnsAllowedMethods() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Methods", containsString("GET"))
+ .header("Access-Control-Allow-Methods", containsString("PUT"))
+ .header("Access-Control-Allow-Methods", containsString("DELETE"));
+ }
+
+ @Test
+ @Order(13)
+ void optionsPreflightReturnsMaxAge() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Max-Age", equalTo("3000"));
+ }
+
+ @Test
+ @Order(14)
+ void optionsPreflightWildcardAllowedHeadersReturnsStarAllowHeaders() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "PUT")
+ .header("Access-Control-Request-Headers", "Content-Type, Authorization, x-amz-meta-owner")
+ .when()
+ .options("/" + BUCKET + "/upload-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("*"))
+ .header("Access-Control-Allow-Headers", equalTo("*"));
+ }
+
+ @Test
+ @Order(15)
+ void optionsPreflightAlsoWorksOnBucketPath() {
+ given()
+ .header("Origin", "https://app.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET)
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("*"));
+ }
+
+ @Test
+ @Order(16)
+ void optionsPreflightReturnsExposeHeaders() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Expose-Headers", containsString("ETag"));
+ }
+
+ // ── Actual requests receive CORS response headers ─────────────────────────
+
+ @Test
+ @Order(20)
+ void putObjectForCorsActualRequestTests() {
+ given()
+ .contentType("text/plain")
+ .body("hello cors")
+ .when()
+ .put("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(21)
+ void actualGetRequestReceivesAllowOriginHeader() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("*"));
+ }
+
+ @Test
+ @Order(22)
+ void actualGetRequestReceivesVaryOriginHeader() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Vary", containsString("Origin"));
+ }
+
+ @Test
+ @Order(23)
+ void actualGetRequestReceivesExposeHeadersHeader() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Expose-Headers", containsString("ETag"));
+ }
+
+ @Test
+ @Order(24)
+ void requestWithoutOriginHeaderGetsNoCorsHeaders() {
+ given()
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ // ── Specific-origin CORS config ───────────────────────────────────────────
+
+ @Test
+ @Order(30)
+ void replaceCorsConfigWithSpecificOrigin() {
+ given()
+ .contentType("application/xml")
+ .body(SPECIFIC_ORIGIN_CORS_XML)
+ .when()
+ .put("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(31)
+ void optionsPreflightMatchingSpecificOriginReturnsOk() {
+ given()
+ .header("Origin", "https://example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .header("Access-Control-Request-Headers", "Content-Type")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("https://example.com"))
+ .header("Access-Control-Max-Age", equalTo("600"));
+ }
+
+ @Test
+ @Order(32)
+ void optionsPreflightSpecificOriginReturnsAllExposeHeaders() {
+ given()
+ .header("Origin", "https://example.com")
+ .header("Access-Control-Request-Method", "PUT")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Expose-Headers", containsString("ETag"))
+ .header("Access-Control-Expose-Headers", containsString("x-amz-request-id"));
+ }
+
+ @Test
+ @Order(33)
+ void optionsPreflightNonMatchingOriginReturnsForbidden() {
+ given()
+ .header("Origin", "https://attacker.evil.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(34)
+ void optionsPreflightNonMatchingMethodReturnsForbidden() {
+ // DELETE is not listed in the specific-origin rule
+ given()
+ .header("Origin", "https://example.com")
+ .header("Access-Control-Request-Method", "DELETE")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(35)
+ void optionsPreflightNonMatchingRequestHeaderReturnsForbidden() {
+ // X-Custom-Header is not in AllowedHeaders and the rule has no wildcard
+ given()
+ .header("Origin", "https://example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .header("Access-Control-Request-Headers", "X-Custom-Header")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(36)
+ void actualGetRequestMatchingSpecificOriginGetsCorsHeaders() {
+ given()
+ .header("Origin", "https://example.com")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("https://example.com"))
+ .header("Vary", containsString("Origin"));
+ }
+
+ @Test
+ @Order(37)
+ void actualGetRequestNonMatchingOriginGetsNoCorsHeaders() {
+ given()
+ .header("Origin", "https://not-allowed.com")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ // ── Delete CORS config ────────────────────────────────────────────────────
+
+ @Test
+ @Order(40)
+ void deleteCorsConfig() {
+ given()
+ .when()
+ .delete("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(204);
+ }
+
+ @Test
+ @Order(41)
+ void optionsPreflightAfterDeleteCorsReturnsForbidden() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(42)
+ void actualGetAfterDeleteCorsGetsNoCorsHeaders() {
+ given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ // ── OPTIONS without Origin is not a preflight ─────────────────────────────
+
+ @Test
+ @Order(50)
+ void optionsWithoutOriginHeaderReturnsOkWithNoCorsHeaders() {
+ given()
+ .when()
+ .options("/" + BUCKET + "/some-key")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ // ── Glob / wildcard origin matching ───────────────────────────────────────
+
+ @Test
+ @Order(60)
+ void putCorsConfigWithSubdomainWildcard() {
+ given()
+ .contentType("application/xml")
+ .body(SUBDOMAIN_WILDCARD_CORS_XML)
+ .when()
+ .put("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(61)
+ void preflightSubdomainWildcardMatchesSubdomain() {
+ given()
+ .header("Origin", "http://foo.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("http://foo.example.com"));
+ }
+
+ @Test
+ @Order(62)
+ void preflightSubdomainWildcardMatchesDeeperSubdomain() {
+ // * matches any string, including one with dots, so bar.baz.example.com is valid
+ given()
+ .header("Origin", "http://bar.baz.example.com")
+ .header("Access-Control-Request-Method", "PUT")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("http://bar.baz.example.com"));
+ }
+
+ @Test
+ @Order(63)
+ void preflightSubdomainWildcardRejectsDifferentScheme() {
+ // Pattern is http://* so https:// must not match
+ given()
+ .header("Origin", "https://foo.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(64)
+ void preflightSubdomainWildcardRejectsDifferentDomain() {
+ given()
+ .header("Origin", "http://foo.other.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(65)
+ void putCorsConfigWithMidStringWildcard() {
+ given()
+ .contentType("application/xml")
+ .body(MID_WILDCARD_CORS_XML)
+ .when()
+ .put("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(66)
+ void preflightMidStringWildcardMatchesVariant() {
+ given()
+ .header("Origin", "http://app-v1.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("http://app-v1.example.com"));
+ }
+
+ @Test
+ @Order(67)
+ void preflightMidStringWildcardMatchesAnotherVariant() {
+ given()
+ .header("Origin", "http://app-staging.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("http://app-staging.example.com"));
+ }
+
+ @Test
+ @Order(68)
+ void preflightMidStringWildcardRejectsNonMatchingPrefix() {
+ // "web-v1.example.com" does not start with "app-"
+ given()
+ .header("Origin", "http://web-v1.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(69)
+ void wildcardMatchAllowsZeroCharactersForStar() {
+ // http://app-.example.com — the * matches the empty string
+ given()
+ .header("Origin", "http://app-.example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .when()
+ .options("/" + BUCKET + "/k")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("http://app-.example.com"));
+ }
+
+ // ── Vary header is not duplicated on repeated actual requests ─────────────
+
+ @Test
+ @Order(70)
+ void putCorsConfigWildcardForVaryTest() {
+ given()
+ .contentType("application/xml")
+ .body(WILDCARD_CORS_XML)
+ .when()
+ .put("/" + BUCKET + "?cors")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(71)
+ void varyOriginAppearsExactlyOnceOnActualRequest() {
+ // Collect the raw Vary header values and count "Origin" occurrences
+ String vary = given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("*"))
+ .extract().header("Vary");
+
+ // Vary may be a single comma-separated string or multiple header lines;
+ // either way "Origin" should appear exactly once.
+ long count = java.util.Arrays.stream(vary.split(","))
+ .map(String::trim)
+ .filter("Origin"::equalsIgnoreCase)
+ .count();
+ org.junit.jupiter.api.Assertions.assertEquals(1, count,
+ "Vary: Origin should appear exactly once, got: " + vary);
+ }
+
+ @Test
+ @Order(72)
+ void accessControlAllowOriginAppearsExactlyOnce() {
+ io.restassured.response.Response resp = given()
+ .header("Origin", "http://localhost:3000")
+ .when()
+ .get("/" + BUCKET + "/hello.txt")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ // getHeaders() returns all values including duplicates
+ long count = resp.headers().getList("Access-Control-Allow-Origin").stream().count();
+ org.junit.jupiter.api.Assertions.assertEquals(1, count,
+ "Access-Control-Allow-Origin must appear exactly once");
+ }
+}
\ No newline at end of file