mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(s3): Evaluate S3 CORS against incoming HTTP Requests (#131)
This commit is contained in:
1 parent
ef06fc3493
commit
e78c833794
5 files changed
+887
-1
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user