mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects (#1736)
* fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects Object keys containing a literal '+' (for example Airflow task-log keys such as run_id=2026-06-26T00:00:00+00:00/f.log) came back from ListObjectsV2 with the '+' turned into a space, so a list-then-get round trip failed with NoSuchKey. '+' only means space in form-encoded query strings, never in URL paths, so every URLDecoder.decode call site on a path or copy source now escapes it first. Also adds encoding-type=url support to ListObjects, ListObjectsV2 and ListObjectVersions: Key, Prefix, Delimiter, StartAfter, Marker/NextMarker and KeyMarker/NextKeyMarker are percent-encoded through a new maybeEncode helper, while the opaque ContinuationToken/NextContinuationToken stay verbatim per the S3 spec. Query parameters the JAX-RS layer has already decoded are not decoded a second time, so keys holding literal percent escapes survive a list round trip. ListObjectVersions honours delimiter, returning CommonPrefixes and the encoded Delimiter, and pages the combined version/prefix result set. Closes #1589 * fix(s3): page ListObjectVersions by entry and honour version-id-marker max-keys grouped every version of a key into a single slot, so a bucket holding two versions of log.txt answered ?versions&max-keys=1 with both Version entries and IsTruncated=false. AWS counts each Version, each DeleteMarker and each CommonPrefixes group as one entry, so a page can stop part-way through a key. Version entries are now emitted one slot at a time, merged with common prefixes in key order. A truncated response carries NextVersionIdMarker beside NextKeyMarker, ListObjectVersions accepts version-id-marker to resume inside a key, and the echoed VersionIdMarker stays verbatim because version ids are opaque. A version-id-marker sent without a key-marker is rejected with InvalidArgument, as on AWS.
This commit is contained in:
1 parent
fc74987bd3
commit
93b6f5e2b0
3 files changed
+458
-38
No files matched your search
@@ -422,6 +422,7 @@ public class S3Controller {
|
||||
@QueryParam("start-after") String startAfter,
|
||||
@QueryParam("encoding-type") String encodingType,
|
||||
@QueryParam("key-marker") String keyMarker,
|
||||
@QueryParam("version-id-marker") String versionIdMarker,
|
||||
@QueryParam("marker") String marker,
|
||||
@Context UriInfo uriInfo,
|
||||
@Context HttpHeaders httpHeaders) {
|
||||
@@ -443,7 +444,8 @@ public class S3Controller {
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "versions")) {
|
||||
s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization);
|
||||
return handleListObjectVersions(bucket, prefix, maxKeys, keyMarker);
|
||||
return handleListObjectVersions(bucket, prefix, delimiter, maxKeys, keyMarker, versionIdMarker,
|
||||
encodingType);
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "location")) {
|
||||
s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization);
|
||||
@@ -531,8 +533,8 @@ public class S3Controller {
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("ListBucketResult", AwsNamespaces.S3)
|
||||
.elem("Name", bucket)
|
||||
.elem("Prefix", prefix != null ? prefix : "")
|
||||
.elem("Delimiter", delimiter)
|
||||
.elem("Prefix", maybeEncode(prefix != null ? prefix : "", encodingType))
|
||||
.elem("Delimiter", maybeEncode(delimiter, encodingType))
|
||||
.elem("MaxKeys", max);
|
||||
if (v2) {
|
||||
xml.elem("KeyCount", objects.size() + commonPrefixes.size());
|
||||
@@ -540,7 +542,7 @@ public class S3Controller {
|
||||
xml.elem("IsTruncated", result.isTruncated());
|
||||
for (S3Object obj : objects) {
|
||||
xml.start("Contents")
|
||||
.elem("Key", obj.getKey())
|
||||
.elem("Key", maybeEncode(obj.getKey(), encodingType))
|
||||
.elem("LastModified", ISO_FORMAT.format(obj.getLastModified()))
|
||||
.elem("ETag", obj.getETag())
|
||||
.elem("Size", obj.getSize())
|
||||
@@ -549,7 +551,7 @@ public class S3Controller {
|
||||
}
|
||||
for (String cp : commonPrefixes) {
|
||||
xml.start("CommonPrefixes")
|
||||
.elem("Prefix", cp)
|
||||
.elem("Prefix", maybeEncode(cp, encodingType))
|
||||
.end("CommonPrefixes");
|
||||
}
|
||||
if (encodingType != null) {
|
||||
@@ -563,12 +565,12 @@ public class S3Controller {
|
||||
xml.elem("NextContinuationToken", result.nextContinuationToken());
|
||||
}
|
||||
if (startAfter != null) {
|
||||
xml.elem("StartAfter", startAfter);
|
||||
xml.elem("StartAfter", maybeEncode(startAfter, encodingType));
|
||||
}
|
||||
} else {
|
||||
xml.elem("Marker", marker != null ? marker : "");
|
||||
xml.elem("Marker", maybeEncode(marker != null ? marker : "", encodingType));
|
||||
if (result.isTruncated() && result.nextContinuationToken() != null) {
|
||||
xml.elem("NextMarker", result.nextContinuationToken());
|
||||
xml.elem("NextMarker", maybeEncode(result.nextContinuationToken(), encodingType));
|
||||
}
|
||||
}
|
||||
xml.end("ListBucketResult");
|
||||
@@ -1378,31 +1380,43 @@ public class S3Controller {
|
||||
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
private Response handleListObjectVersions(String bucket, String prefix, Integer maxKeys, String keyMarker) {
|
||||
private Response handleListObjectVersions(String bucket, String prefix, String delimiter, Integer maxKeys,
|
||||
String keyMarker, String versionIdMarker, String encodingType) {
|
||||
if (hasText(versionIdMarker) && !hasText(keyMarker)) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"A version-id marker cannot be specified without a key marker.", 400);
|
||||
}
|
||||
int max = (maxKeys != null && maxKeys > 0) ? maxKeys : 1000;
|
||||
S3Service.ListVersionsResult result = s3Service.listObjectVersions(bucket, prefix, max, keyMarker);
|
||||
S3Service.ListVersionsResult result =
|
||||
s3Service.listObjectVersions(bucket, prefix, delimiter, max, keyMarker, versionIdMarker);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("ListVersionsResult", AwsNamespaces.S3)
|
||||
.elem("Name", bucket)
|
||||
.elem("Prefix", prefix)
|
||||
.elem("KeyMarker", keyMarker)
|
||||
.elem("MaxKeys", max)
|
||||
.elem("IsTruncated", result.isTruncated());
|
||||
.elem("Prefix", maybeEncode(prefix, encodingType))
|
||||
.elem("KeyMarker", maybeEncode(keyMarker, encodingType))
|
||||
// Version ids are opaque, so they are echoed verbatim like ContinuationToken.
|
||||
.elem("VersionIdMarker", versionIdMarker);
|
||||
if (delimiter != null) {
|
||||
xml.elem("Delimiter", maybeEncode(delimiter, encodingType));
|
||||
}
|
||||
xml.elem("MaxKeys", max)
|
||||
.elem("IsTruncated", result.isTruncated());
|
||||
if (result.isTruncated()) {
|
||||
xml.elem("NextKeyMarker", result.nextKeyMarker());
|
||||
xml.elem("NextKeyMarker", maybeEncode(result.nextKeyMarker(), encodingType));
|
||||
xml.elem("NextVersionIdMarker", result.nextVersionIdMarker());
|
||||
}
|
||||
for (S3Object obj : result.versions()) {
|
||||
if (obj.isDeleteMarker()) {
|
||||
xml.start("DeleteMarker")
|
||||
.elem("Key", obj.getKey())
|
||||
.elem("Key", maybeEncode(obj.getKey(), encodingType))
|
||||
.elem("VersionId", obj.getVersionId())
|
||||
.elem("IsLatest", obj.isLatest())
|
||||
.elem("LastModified", ISO_FORMAT.format(obj.getLastModified()))
|
||||
.end("DeleteMarker");
|
||||
} else {
|
||||
xml.start("Version")
|
||||
.elem("Key", obj.getKey())
|
||||
.elem("Key", maybeEncode(obj.getKey(), encodingType))
|
||||
.elem("VersionId", obj.getVersionId() != null ? obj.getVersionId() : "null")
|
||||
.elem("IsLatest", obj.isLatest())
|
||||
.elem("LastModified", ISO_FORMAT.format(obj.getLastModified()))
|
||||
@@ -1412,6 +1426,14 @@ public class S3Controller {
|
||||
.end("Version");
|
||||
}
|
||||
}
|
||||
for (String cp : result.commonPrefixes()) {
|
||||
xml.start("CommonPrefixes")
|
||||
.elem("Prefix", maybeEncode(cp, encodingType))
|
||||
.end("CommonPrefixes");
|
||||
}
|
||||
if (encodingType != null) {
|
||||
xml.elem("EncodingType", encodingType);
|
||||
}
|
||||
xml.end("ListVersionsResult");
|
||||
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
@@ -2895,7 +2917,7 @@ public class S3Controller {
|
||||
return uriInfo.getPathParameters().getFirst("key");
|
||||
}
|
||||
String rawKey = rawPath.substring(prefixIndex + bucketPrefix.length());
|
||||
String key = URLDecoder.decode(rawKey, StandardCharsets.UTF_8);
|
||||
String key = URLDecoder.decode(rawKey.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
validateKeyNoTraversal(key);
|
||||
return key;
|
||||
}
|
||||
@@ -2924,7 +2946,7 @@ public class S3Controller {
|
||||
String rawPath = queryIndex >= 0 ? rawUri.substring(0, queryIndex) : rawUri;
|
||||
String decodedPath;
|
||||
try {
|
||||
decodedPath = URLDecoder.decode(rawPath, StandardCharsets.UTF_8);
|
||||
decodedPath = URLDecoder.decode(rawPath.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
throw new AwsException("BadRequest", null, 400);
|
||||
@@ -3105,7 +3127,7 @@ public class S3Controller {
|
||||
|
||||
private String decodeCopySourceComponent(String value, String originalCopySource) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidArgument", "Invalid copy source: " + originalCopySource, 400);
|
||||
}
|
||||
@@ -3116,4 +3138,29 @@ public class S3Controller {
|
||||
|
||||
private record CopySourceRef(String bucket, String objectKey, String versionId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-encodes a response field when the request asked for {@code encoding-type=url}.
|
||||
*
|
||||
* <p>Applied only to the fields AWS encodes ({@code Key}, {@code Prefix}, {@code Delimiter},
|
||||
* {@code StartAfter}, {@code Marker}/{@code NextMarker} and {@code KeyMarker}/{@code NextKeyMarker}).
|
||||
* Opaque tokens such as {@code ContinuationToken} and version ids are returned verbatim so clients can
|
||||
* feed them straight back as query parameters.
|
||||
*
|
||||
* <p>{@code URLEncoder} emits {@code application/x-www-form-urlencoded} output, so the result is
|
||||
* post-processed into the RFC 3986 form S3 uses: {@code '+'} back to {@code %20}, {@code '*'} to
|
||||
* {@code %2A} and {@code %7E} back to a literal {@code '~'}.
|
||||
*/
|
||||
private String maybeEncode(String val, String encodingType) {
|
||||
if (val == null) {
|
||||
return null;
|
||||
}
|
||||
if ("url".equalsIgnoreCase(encodingType)) {
|
||||
return java.net.URLEncoder.encode(val, StandardCharsets.UTF_8)
|
||||
.replace("+", "%20")
|
||||
.replace("*", "%2A")
|
||||
.replace("%7E", "~");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
}
|
||||
@@ -1158,9 +1158,27 @@ public class S3Service implements Resettable {
|
||||
return bucket.getVersioningStatus();
|
||||
}
|
||||
|
||||
public record ListVersionsResult(List<S3Object> versions, boolean isTruncated, String nextKeyMarker) {}
|
||||
public record ListVersionsResult(List<S3Object> versions, List<String> commonPrefixes, boolean isTruncated,
|
||||
String nextKeyMarker, String nextVersionIdMarker) {}
|
||||
|
||||
public ListVersionsResult listObjectVersions(String bucketName, String prefix, int maxKeys, String keyMarker) {
|
||||
return listObjectVersions(bucketName, prefix, null, maxKeys, keyMarker, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists every version and delete marker under {@code prefix}, optionally grouped by {@code delimiter}.
|
||||
*
|
||||
* <p>{@code maxKeys} bounds the number of entries in the response, where each {@code Version}, each
|
||||
* {@code DeleteMarker} and each {@code CommonPrefixes} group counts as one entry, exactly as AWS counts
|
||||
* them. A page may therefore end part-way through the versions of a single key, which is why a truncated
|
||||
* response carries both {@code NextKeyMarker} and {@code NextVersionIdMarker}: the pair identifies the
|
||||
* last entry returned, and the next request resumes at the entry immediately after it.
|
||||
*
|
||||
* @param versionIdMarker version id of the last entry of the previous page; only meaningful together with
|
||||
* {@code keyMarker}, and ignored when the key it names holds no such version
|
||||
*/
|
||||
public ListVersionsResult listObjectVersions(String bucketName, String prefix, String delimiter, int maxKeys,
|
||||
String keyMarker, String versionIdMarker) {
|
||||
ensureBucketExists(bucketName);
|
||||
|
||||
String versionPrefix = bucketName + "/";
|
||||
@@ -1179,6 +1197,27 @@ public class S3Service implements Resettable {
|
||||
.filter(obj -> obj.getVersionId() == null)
|
||||
.forEach(versions::add);
|
||||
|
||||
List<String> commonPrefixes = List.of();
|
||||
if (delimiter != null && !delimiter.isEmpty()) {
|
||||
Set<String> prefixSet = new LinkedHashSet<>();
|
||||
List<S3Object> directVersions = new ArrayList<>();
|
||||
|
||||
for (S3Object obj : versions) {
|
||||
String remainder = obj.getKey().substring(prefix != null ? prefix.length() : 0);
|
||||
int delimIdx = remainder.indexOf(delimiter);
|
||||
if (delimIdx >= 0) {
|
||||
String cp = (prefix != null ? prefix : "") + remainder.substring(0, delimIdx + delimiter.length());
|
||||
prefixSet.add(cp);
|
||||
} else {
|
||||
directVersions.add(obj);
|
||||
}
|
||||
}
|
||||
|
||||
versions = directVersions;
|
||||
commonPrefixes = new ArrayList<>(prefixSet);
|
||||
Collections.sort(commonPrefixes);
|
||||
}
|
||||
|
||||
// Sort by key, then by lastModified descending
|
||||
versions.sort((a, b) -> {
|
||||
int keyCompare = a.getKey().compareTo(b.getKey());
|
||||
@@ -1186,33 +1225,84 @@ public class S3Service implements Resettable {
|
||||
return b.getLastModified().compareTo(a.getLastModified());
|
||||
});
|
||||
|
||||
// Apply key-marker filter: skip objects whose key is <= keyMarker
|
||||
// Apply the marker filter. Without a version-id-marker the marker is an exclusive lower bound on the
|
||||
// key; with one, the previous page stopped inside keyMarker, so the versions of that key that follow
|
||||
// the named version are still owed to the caller.
|
||||
if (keyMarker != null && !keyMarker.isEmpty()) {
|
||||
final String km = keyMarker;
|
||||
versions = versions.stream()
|
||||
.filter(v -> v.getKey().compareTo(km) > 0)
|
||||
commonPrefixes = commonPrefixes.stream()
|
||||
.filter(cp -> cp.compareTo(km) > 0)
|
||||
.collect(java.util.stream.Collectors.toCollection(ArrayList::new));
|
||||
|
||||
if (versionIdMarker != null && !versionIdMarker.isEmpty()) {
|
||||
List<S3Object> remaining = new ArrayList<>();
|
||||
boolean afterMarker = false;
|
||||
for (S3Object v : versions) {
|
||||
int keyCompare = v.getKey().compareTo(km);
|
||||
if (keyCompare < 0) {
|
||||
continue;
|
||||
}
|
||||
if (keyCompare > 0 || afterMarker) {
|
||||
remaining.add(v);
|
||||
} else if (versionIdMarker.equals(reportedVersionId(v))) {
|
||||
afterMarker = true;
|
||||
}
|
||||
}
|
||||
versions = remaining;
|
||||
} else {
|
||||
versions = versions.stream()
|
||||
.filter(v -> v.getKey().compareTo(km) > 0)
|
||||
.collect(java.util.stream.Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
}
|
||||
|
||||
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++;
|
||||
String nextVersionIdMarker = null;
|
||||
if (maxKeys > 0) {
|
||||
List<S3Object> pageVersions = new ArrayList<>();
|
||||
List<String> pagePrefixes = new ArrayList<>();
|
||||
int vIdx = 0;
|
||||
int cpIdx = 0;
|
||||
|
||||
// Merge versions and common prefixes in key order, one response entry at a time, so that
|
||||
// maxKeys bounds Version/DeleteMarker entries as well as CommonPrefixes groups.
|
||||
while (pageVersions.size() + pagePrefixes.size() < maxKeys
|
||||
&& (vIdx < versions.size() || cpIdx < commonPrefixes.size())) {
|
||||
String vKey = vIdx < versions.size() ? versions.get(vIdx).getKey() : null;
|
||||
String cpKey = cpIdx < commonPrefixes.size() ? commonPrefixes.get(cpIdx) : null;
|
||||
|
||||
if (vKey != null && (cpKey == null || vKey.compareTo(cpKey) <= 0)) {
|
||||
S3Object version = versions.get(vIdx++);
|
||||
pageVersions.add(version);
|
||||
nextKeyMarker = version.getKey();
|
||||
nextVersionIdMarker = reportedVersionId(version);
|
||||
} else {
|
||||
String commonPrefix = commonPrefixes.get(cpIdx++);
|
||||
pagePrefixes.add(commonPrefix);
|
||||
nextKeyMarker = commonPrefix;
|
||||
nextVersionIdMarker = null;
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
||||
isTruncated = vIdx < versions.size() || cpIdx < commonPrefixes.size();
|
||||
if (!isTruncated) {
|
||||
nextKeyMarker = null;
|
||||
nextVersionIdMarker = null;
|
||||
}
|
||||
versions = new ArrayList<>(versions.subList(0, cutoff));
|
||||
versions = pageVersions;
|
||||
commonPrefixes = pagePrefixes;
|
||||
}
|
||||
return new ListVersionsResult(versions, isTruncated, nextKeyMarker);
|
||||
return new ListVersionsResult(versions, commonPrefixes, isTruncated, nextKeyMarker, nextVersionIdMarker);
|
||||
}
|
||||
|
||||
/**
|
||||
* Version id as it appears in a {@code ListObjectVersions} response: objects stored while versioning was
|
||||
* off have no version id, and AWS reports those as the literal string {@code "null"}. Markers echoed back
|
||||
* by a client therefore have to be compared against that same rendering.
|
||||
*/
|
||||
private static String reportedVersionId(S3Object object) {
|
||||
return object.getVersionId() != null ? object.getVersionId() : "null";
|
||||
}
|
||||
|
||||
// --- Head Bucket / Bucket Location ---
|
||||
|
||||
Reference in new issue
Block a user