mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(s3): versioning IsTruncated, PublicAccessBlock, ListObjectsV2 pagination, K8s virtual host routing (#276)
This commit is contained in:
1 parent
399a96d70c
commit
6d5839bec8
10 files changed
+797
-60
No files matched your search
@@ -159,6 +159,10 @@ public class S3Controller {
|
||||
s3Service.putBucketEncryption(bucket, new String(body, StandardCharsets.UTF_8));
|
||||
return Response.ok().build();
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "publicAccessBlock")) {
|
||||
s3Service.putPublicAccessBlock(bucket, new String(body, StandardCharsets.UTF_8));
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
String locationConstraint = null;
|
||||
if (body != null && body.length > 0) {
|
||||
@@ -214,6 +218,10 @@ public class S3Controller {
|
||||
s3Service.deleteBucketEncryption(bucket);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "publicAccessBlock")) {
|
||||
s3Service.deletePublicAccessBlock(bucket);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
s3Service.deleteBucket(bucket);
|
||||
return Response.noContent().build();
|
||||
} catch (AwsException e) {
|
||||
@@ -231,6 +239,8 @@ public class S3Controller {
|
||||
@QueryParam("list-type") String listType,
|
||||
@QueryParam("continuation-token") String continuationToken,
|
||||
@QueryParam("start-after") String startAfter,
|
||||
@QueryParam("encoding-type") String encodingType,
|
||||
@QueryParam("key-marker") String keyMarker,
|
||||
@Context UriInfo uriInfo) {
|
||||
try {
|
||||
if (hasQueryParam(uriInfo, "uploads")) {
|
||||
@@ -243,7 +253,7 @@ public class S3Controller {
|
||||
return handleGetBucketVersioning(bucket);
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "versions")) {
|
||||
return handleListObjectVersions(bucket, prefix, maxKeys);
|
||||
return handleListObjectVersions(bucket, prefix, maxKeys, keyMarker);
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "location")) {
|
||||
return handleGetBucketLocation(bucket);
|
||||
@@ -269,9 +279,13 @@ public class S3Controller {
|
||||
if (hasQueryParam(uriInfo, "encryption")) {
|
||||
return Response.ok(s3Service.getBucketEncryption(bucket)).build();
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "publicAccessBlock")) {
|
||||
return Response.ok(s3Service.getPublicAccessBlock(bucket)).build();
|
||||
}
|
||||
|
||||
int max = (maxKeys != null && maxKeys > 0) ? maxKeys : 1000;
|
||||
S3Service.ListObjectsResult result = s3Service.listObjectsWithPrefixes(bucket, prefix, delimiter, max);
|
||||
S3Service.ListObjectsResult result = s3Service.listObjectsWithPrefixes(
|
||||
bucket, prefix, delimiter, max, continuationToken, startAfter);
|
||||
List<S3Object> objects = result.objects();
|
||||
List<String> commonPrefixes = result.commonPrefixes();
|
||||
boolean v2 = "2".equals(listType);
|
||||
@@ -301,6 +315,20 @@ public class S3Controller {
|
||||
.elem("Prefix", cp)
|
||||
.end("CommonPrefixes");
|
||||
}
|
||||
if (encodingType != null) {
|
||||
xml.elem("EncodingType", encodingType);
|
||||
}
|
||||
if (v2) {
|
||||
if (continuationToken != null) {
|
||||
xml.elem("ContinuationToken", continuationToken);
|
||||
}
|
||||
if (result.isTruncated()) {
|
||||
xml.elem("NextContinuationToken", result.nextContinuationToken());
|
||||
}
|
||||
if (startAfter != null) {
|
||||
xml.elem("StartAfter", startAfter);
|
||||
}
|
||||
}
|
||||
xml.end("ListBucketResult");
|
||||
return Response.ok(xml.build()).build();
|
||||
} catch (AwsException e) {
|
||||
@@ -880,16 +908,21 @@ public class S3Controller {
|
||||
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
private Response handleListObjectVersions(String bucket, String prefix, Integer maxKeys) {
|
||||
private Response handleListObjectVersions(String bucket, String prefix, Integer maxKeys, String keyMarker) {
|
||||
int max = (maxKeys != null && maxKeys > 0) ? maxKeys : 1000;
|
||||
List<S3Object> versions = s3Service.listObjectVersions(bucket, prefix, max);
|
||||
S3Service.ListVersionsResult result = s3Service.listObjectVersions(bucket, prefix, max, keyMarker);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("ListVersionsResult", AwsNamespaces.S3)
|
||||
.elem("Name", bucket)
|
||||
.elem("Prefix", prefix)
|
||||
.elem("MaxKeys", max);
|
||||
for (S3Object obj : versions) {
|
||||
.elem("KeyMarker", keyMarker)
|
||||
.elem("MaxKeys", max)
|
||||
.elem("IsTruncated", result.isTruncated());
|
||||
if (result.isTruncated()) {
|
||||
xml.elem("NextKeyMarker", result.nextKeyMarker());
|
||||
}
|
||||
for (S3Object obj : result.versions()) {
|
||||
if (obj.isDeleteMarker()) {
|
||||
xml.start("DeleteMarker")
|
||||
.elem("Key", obj.getKey())
|
||||
|
||||
@@ -440,13 +440,18 @@ public class S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
public record ListObjectsResult(List<S3Object> objects, List<String> commonPrefixes, boolean isTruncated) {}
|
||||
public record ListObjectsResult(List<S3Object> objects, List<String> commonPrefixes, boolean isTruncated, String nextContinuationToken) {}
|
||||
|
||||
public List<S3Object> listObjects(String bucketName, String prefix, String delimiter, int maxKeys) {
|
||||
return listObjectsWithPrefixes(bucketName, prefix, delimiter, maxKeys).objects();
|
||||
return listObjectsWithPrefixes(bucketName, prefix, delimiter, maxKeys, null, null).objects();
|
||||
}
|
||||
|
||||
public ListObjectsResult listObjectsWithPrefixes(String bucketName, String prefix, String delimiter, int maxKeys) {
|
||||
return listObjectsWithPrefixes(bucketName, prefix, delimiter, maxKeys, null, null);
|
||||
}
|
||||
|
||||
public ListObjectsResult listObjectsWithPrefixes(String bucketName, String prefix, String delimiter, int maxKeys,
|
||||
String continuationToken, String startAfter) {
|
||||
ensureBucketExists(bucketName);
|
||||
|
||||
String keyPrefix = bucketName + "/";
|
||||
@@ -485,34 +490,54 @@ public class S3Service {
|
||||
|
||||
allObjects.sort(Comparator.comparing(S3Object::getKey));
|
||||
|
||||
// Apply continuation-token / start-after filter.
|
||||
// continuation-token takes precedence; it encodes the last key seen on a previous page.
|
||||
String filterKey = continuationToken != null ? continuationToken : startAfter;
|
||||
if (filterKey != null) {
|
||||
final String fk = filterKey;
|
||||
allObjects = allObjects.stream()
|
||||
.filter(o -> o.getKey().compareTo(fk) > 0)
|
||||
.collect(java.util.stream.Collectors.toCollection(ArrayList::new));
|
||||
commonPrefixes = commonPrefixes.stream()
|
||||
.filter(cp -> cp.compareTo(fk) > 0)
|
||||
.collect(java.util.stream.Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
|
||||
// S3 counts both direct objects and common prefixes.
|
||||
// Each common prefix group (e.g. "docs/") uses one entry regardless of
|
||||
// how many keys it contains. Merge both sorted lists lexicographically
|
||||
// and stop at maxKeys to try to match S3 ListObjectsV2 behavior.
|
||||
// see https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
|
||||
boolean isTruncated = false;
|
||||
String nextContinuationToken = null;
|
||||
if (maxKeys > 0) {
|
||||
List<S3Object> limitedObjects = new ArrayList<>();
|
||||
List<String> limitedPrefixes = new ArrayList<>();
|
||||
int count = 0;
|
||||
int directObjectCount = 0;
|
||||
int commonPrefixCount = 0;
|
||||
String lastEmittedKey = null;
|
||||
while (count < maxKeys && (directObjectCount < allObjects.size() || commonPrefixCount < commonPrefixes.size())) {
|
||||
String objectKey = directObjectCount < allObjects.size() ? allObjects.get(directObjectCount).getKey() : null;
|
||||
String prefixKey = commonPrefixCount < commonPrefixes.size() ? commonPrefixes.get(commonPrefixCount) : null;
|
||||
if (objectKey != null && (prefixKey == null || objectKey.compareTo(prefixKey) <= 0)) {
|
||||
limitedObjects.add(allObjects.get(directObjectCount++));
|
||||
lastEmittedKey = objectKey;
|
||||
} else {
|
||||
limitedPrefixes.add(commonPrefixes.get(commonPrefixCount++));
|
||||
lastEmittedKey = prefixKey;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
isTruncated = directObjectCount < allObjects.size() || commonPrefixCount < commonPrefixes.size();
|
||||
if (isTruncated) {
|
||||
nextContinuationToken = lastEmittedKey;
|
||||
}
|
||||
allObjects = limitedObjects;
|
||||
commonPrefixes = limitedPrefixes;
|
||||
}
|
||||
|
||||
return new ListObjectsResult(allObjects, commonPrefixes, isTruncated);
|
||||
return new ListObjectsResult(allObjects, commonPrefixes, isTruncated, nextContinuationToken);
|
||||
}
|
||||
|
||||
public S3Object copyObject(String sourceBucket, String sourceKey,
|
||||
@@ -576,7 +601,9 @@ public class S3Service {
|
||||
return bucket.getVersioningStatus();
|
||||
}
|
||||
|
||||
public List<S3Object> listObjectVersions(String bucketName, String prefix, int maxKeys) {
|
||||
public record ListVersionsResult(List<S3Object> versions, boolean isTruncated, String nextKeyMarker) {}
|
||||
|
||||
public ListVersionsResult listObjectVersions(String bucketName, String prefix, int maxKeys, String keyMarker) {
|
||||
ensureBucketExists(bucketName);
|
||||
|
||||
String versionPrefix = bucketName + "/";
|
||||
@@ -593,10 +620,33 @@ public class S3Service {
|
||||
return b.getLastModified().compareTo(a.getLastModified());
|
||||
});
|
||||
|
||||
if (maxKeys > 0 && versions.size() > maxKeys) {
|
||||
versions = versions.subList(0, maxKeys);
|
||||
// Apply key-marker filter: skip objects whose key is <= keyMarker
|
||||
if (keyMarker != null && !keyMarker.isEmpty()) {
|
||||
final String km = keyMarker;
|
||||
versions = versions.stream()
|
||||
.filter(v -> v.getKey().compareTo(km) > 0)
|
||||
.collect(java.util.stream.Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
return versions;
|
||||
|
||||
boolean isTruncated = false;
|
||||
String nextKeyMarker = null;
|
||||
if (maxKeys > 0 && versions.size() > maxKeys) {
|
||||
// Extend the cutoff to avoid splitting versions of the same key across pages.
|
||||
// All versions of the same key must appear on the same page.
|
||||
int cutoff = maxKeys;
|
||||
String lastKey = versions.get(maxKeys - 1).getKey();
|
||||
while (cutoff < versions.size() && versions.get(cutoff).getKey().equals(lastKey)) {
|
||||
cutoff++;
|
||||
}
|
||||
isTruncated = cutoff < versions.size();
|
||||
if (isTruncated) {
|
||||
// nextKeyMarker is used as an exclusive lower bound: next page gets key > nextKeyMarker.
|
||||
// Set it to the last included key so the next page starts right after it.
|
||||
nextKeyMarker = versions.get(cutoff - 1).getKey();
|
||||
}
|
||||
versions = new ArrayList<>(versions.subList(0, cutoff));
|
||||
}
|
||||
return new ListVersionsResult(versions, isTruncated, nextKeyMarker);
|
||||
}
|
||||
|
||||
// --- Head Bucket / Bucket Location ---
|
||||
@@ -1191,6 +1241,30 @@ public class S3Service {
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
|
||||
public String getPublicAccessBlock(String bucketName) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
if (bucket.getPublicAccessBlockConfiguration() == null) {
|
||||
throw new AwsException("NoSuchPublicAccessBlockConfiguration",
|
||||
"The public access block configuration was not found", 404);
|
||||
}
|
||||
return bucket.getPublicAccessBlockConfiguration();
|
||||
}
|
||||
|
||||
public void putPublicAccessBlock(String bucketName, String xml) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
bucket.setPublicAccessBlockConfiguration(xml);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
|
||||
public void deletePublicAccessBlock(String bucketName) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
bucket.setPublicAccessBlockConfiguration(null);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
|
||||
public void restoreObject(String bucketName, String key, String versionId, String restoreXml) {
|
||||
// Validation only - stub implementation
|
||||
getObject(bucketName, key, versionId);
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.core.UriBuilder;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Optional;
|
||||
|
||||
@Provider
|
||||
@PreMatching
|
||||
public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
|
||||
private final String baseHostname;
|
||||
|
||||
@Inject
|
||||
public S3VirtualHostFilter(
|
||||
@ConfigProperty(name = "floci.base-url", defaultValue = "http://localhost:4566") String baseUrl,
|
||||
@ConfigProperty(name = "floci.hostname") Optional<String> hostname) {
|
||||
String effectiveUrl = hostname
|
||||
.map(h -> baseUrl.replaceFirst("://[^:/]+(:\\d+)?", "://" + h + "$1"))
|
||||
.orElse(baseUrl);
|
||||
this.baseHostname = extractHostnameFromUrl(effectiveUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) {
|
||||
String host = requestContext.getHeaderString("Host");
|
||||
@@ -22,7 +38,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
// S3 does not use these content types for bucket/object operations,
|
||||
// S3 does not use these content types for bucket/object operations,
|
||||
// but other AWS services (AwsQuery, JSON protocols) do.
|
||||
String contentType = requestContext.getHeaderString("Content-Type");
|
||||
if (contentType != null && (
|
||||
@@ -31,7 +47,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
String bucket = extractBucket(host);
|
||||
String bucket = extractBucket(host, baseHostname);
|
||||
if (bucket == null) return;
|
||||
|
||||
URI uri = requestContext.getUriInfo().getRequestUri();
|
||||
@@ -50,28 +66,27 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
/**
|
||||
* Extracts a bucket name from a virtual-hosted-style Host header.
|
||||
*
|
||||
* The first label of the hostname (before the first dot) is treated as the
|
||||
* bucket name whenever the hostname contains at least one dot and is not an
|
||||
* IP address. This works for any endpoint hostname — localhost, custom hosts,
|
||||
* or S3-style domains — without requiring configuration.
|
||||
* A request is considered virtual-hosted-style when the hostname's remainder
|
||||
* after the first label matches the configured Floci base hostname, or when it
|
||||
* matches a well-known AWS S3 domain pattern (for DNS-redirect setups).
|
||||
*
|
||||
* Note: AWS SDKs automatically fall back to path-style for bucket names that
|
||||
* contain dots, so the first-label heuristic is sufficient.
|
||||
* Examples with baseHostname="localhost":
|
||||
* my-bucket.localhost:4566 → "my-bucket"
|
||||
* my-bucket.localhost → "my-bucket"
|
||||
* floci.svc.cluster.local → null (no bucket prefix, path-style)
|
||||
* my-svc.floci.svc.cluster.local → null (remainder doesn't match "localhost")
|
||||
*
|
||||
* Examples with baseHostname="floci.svc.cluster.local":
|
||||
* my-bucket.floci.svc.cluster.local → "my-bucket"
|
||||
* floci.svc.cluster.local → null (no bucket prefix, path-style)
|
||||
*
|
||||
* Returns null if the host does not match a virtual-hosted pattern.
|
||||
*/
|
||||
static String extractBucket(String host) {
|
||||
static String extractBucket(String host, String baseHostname) {
|
||||
if (host == null) return null;
|
||||
|
||||
// Strip port if present
|
||||
String hostname = host;
|
||||
int colonIndex = hostname.lastIndexOf(':');
|
||||
if (colonIndex > 0) {
|
||||
String maybePart = hostname.substring(colonIndex + 1);
|
||||
if (!maybePart.isEmpty() && maybePart.chars().allMatch(Character::isDigit)) {
|
||||
hostname = hostname.substring(0, colonIndex);
|
||||
}
|
||||
}
|
||||
String hostname = stripPort(host);
|
||||
|
||||
// Need at least one dot for a subdomain to exist
|
||||
int firstDot = hostname.indexOf('.');
|
||||
@@ -84,7 +99,42 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hostname.substring(0, firstDot);
|
||||
String firstLabel = hostname.substring(0, firstDot);
|
||||
String remainder = hostname.substring(firstDot + 1);
|
||||
|
||||
// Primary: remainder must match the configured base hostname
|
||||
if (baseHostname != null && remainder.equalsIgnoreCase(baseHostname)) {
|
||||
return firstLabel;
|
||||
}
|
||||
|
||||
// Fallback: well-known AWS S3 domains, for users who route AWS DNS to Floci
|
||||
if (isAwsS3Domain(remainder)) {
|
||||
return firstLabel;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extracts the hostname (without scheme or port) from a URL string. */
|
||||
static String extractHostnameFromUrl(String url) {
|
||||
if (url == null) return null;
|
||||
try {
|
||||
URI uri = URI.create(url);
|
||||
return uri.getHost();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String stripPort(String host) {
|
||||
int colonIndex = host.lastIndexOf(':');
|
||||
if (colonIndex > 0) {
|
||||
String maybePart = host.substring(colonIndex + 1);
|
||||
if (!maybePart.isEmpty() && maybePart.chars().allMatch(Character::isDigit)) {
|
||||
return host.substring(0, colonIndex);
|
||||
}
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
private static boolean isIpv4Address(String hostname) {
|
||||
@@ -96,4 +146,12 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Returns true for *.s3.amazonaws.com and *.s3.<region>.amazonaws.com domains. */
|
||||
private static boolean isAwsS3Domain(String remainder) {
|
||||
if ("s3.amazonaws.com".equals(remainder)) return true;
|
||||
// s3.<region>.amazonaws.com
|
||||
if (remainder.startsWith("s3.") && remainder.endsWith(".amazonaws.com")) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ public class Bucket {
|
||||
private String lifecycleConfiguration;
|
||||
private String acl; // XML representation or JSON stub
|
||||
private String encryptionConfiguration; // XML string
|
||||
private String publicAccessBlockConfiguration; // XML string
|
||||
private String region;
|
||||
|
||||
public Bucket() {
|
||||
@@ -76,6 +77,11 @@ public class Bucket {
|
||||
public String getEncryptionConfiguration() { return encryptionConfiguration; }
|
||||
public void setEncryptionConfiguration(String encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; }
|
||||
|
||||
public String getPublicAccessBlockConfiguration() { return publicAccessBlockConfiguration; }
|
||||
public void setPublicAccessBlockConfiguration(String publicAccessBlockConfiguration) {
|
||||
this.publicAccessBlockConfiguration = publicAccessBlockConfiguration;
|
||||
}
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
}
|
||||
Reference in new issue
Block a user