fix: Support S3 auth enforcement (#1689)

This commit is contained in:
David Phillips authored and GitHub committed 2026-07-10 22:41:03 -05:00
1 parent 8590ffec34
commit a3e8bf5a8b
18 files changed
+2377 -41

No files matched your search

@@ -710,6 +710,9 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("false")
boolean enforceAuth();
@WithDefault("3600")
int defaultPresignExpirySeconds();
}
@@ -28,16 +28,18 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
if (S3RequestAuthorizationParser.isMissingRequiredPresignedParameter(queryParams)) {
requestContext.abortWith(errorResponse(
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS,
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE,
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE));
return;
}
String amzDate = queryParams.getFirst("X-Amz-Date");
String expiresStr = queryParams.getFirst("X-Amz-Expires");
String signature = queryParams.getFirst("X-Amz-Signature");
if (amzDate == null || expiresStr == null || signature == null) {
requestContext.abortWith(errorResponse(403, "AccessDenied",
"Missing required pre-signed URL parameters."));
return;
}
int expires;
try {
expires = Integer.parseInt(expiresStr);
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.s3;
import org.jboss.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
private static final Logger LOG = Logger.getLogger(S3AclPolicy.class);
static final String ALL_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AllUsers";
static S3AclPolicy parse(String acl) throws AclParseException {
try {
return fromDocument(parseXml(acl));
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new AclParseException(e);
}
}
private static Document parseXml(String acl) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setExpandEntityReferences(false);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SilentThrowingErrorHandler());
return builder.parse(new InputSource(new StringReader(acl)));
}
private static S3AclPolicy fromDocument(Document document) {
Element accessControlPolicy = document.getDocumentElement();
if (accessControlPolicy == null || !"AccessControlPolicy".equals(accessControlPolicy.getLocalName())) {
return new S3AclPolicy(List.of());
}
Element accessControlList = firstChildElement(accessControlPolicy, "AccessControlList");
if (accessControlList == null) {
return new S3AclPolicy(List.of());
}
NodeList grantNodes = accessControlList.getChildNodes();
List<Grant> grants = new ArrayList<>();
for (int index = 0; index < grantNodes.getLength(); index++) {
if (grantNodes.item(index) instanceof Element grantElement && "Grant".equals(grantElement.getLocalName())) {
grants.add(parseGrant(grantElement));
}
}
return new S3AclPolicy(List.copyOf(grants));
}
static final class AclParseException extends Exception {
AclParseException(Throwable cause) {
super("Failed to parse S3 ACL", cause);
}
}
private static Grant parseGrant(Element grantElement) {
Element granteeElement = firstChildElement(grantElement, "Grantee");
String uri = granteeElement != null ? descendantText(granteeElement, "URI") : null;
String permissionText = childText(grantElement, "Permission");
return new Grant(new Grantee(uri), Permission.fromXml(permissionText));
}
private static Element firstChildElement(Element parent, String localName) {
NodeList children = parent.getChildNodes();
for (int index = 0; index < children.getLength(); index++) {
Node child = children.item(index);
if (child instanceof Element element && localName.equals(element.getLocalName())) {
return element;
}
}
return null;
}
private static String childText(Element parent, String localName) {
Element child = firstChildElement(parent, localName);
return child != null ? normalizedText(child) : null;
}
private static String descendantText(Element parent, String localName) {
NodeList nodes = parent.getElementsByTagNameNS("*", localName);
if (nodes.getLength() == 0) {
return null;
}
return normalizedText(nodes.item(0));
}
private static String normalizedText(Node node) {
String text = node.getTextContent();
return text != null ? text.trim() : null;
}
record Grant(Grantee grantee, Permission permission) {
boolean allowsPublicRead() {
return grantee.isAllUsersGroup() && permission.allowsRead();
}
}
record Grantee(String uri) {
boolean isAllUsersGroup() {
return ALL_USERS_GROUP_URI.equals(uri);
}
}
enum Permission {
READ,
WRITE,
READ_ACP,
WRITE_ACP,
FULL_CONTROL,
UNKNOWN;
static Permission fromXml(String value) {
if (value == null || value.isBlank()) {
return UNKNOWN;
}
try {
return Permission.valueOf(value.trim());
} catch (IllegalArgumentException e) {
return UNKNOWN;
}
}
boolean allowsRead() {
return this == READ || this == FULL_CONTROL;
}
}
private static final class SilentThrowingErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) {
}
@Override
public void error(SAXParseException exception) {
LOG.debugv(exception, "Recoverable S3 ACL XML parse error");
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
}
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.s3;
import org.jboss.logging.Logger;
final class S3AclPublicAccessEvaluator {
static final String ALL_USERS_GROUP_URI = S3AclPolicy.ALL_USERS_GROUP_URI;
private static final Logger LOG = Logger.getLogger(S3AclPublicAccessEvaluator.class);
private S3AclPublicAccessEvaluator() {
}
static boolean aclAllowsPublicRead(String acl) {
if (acl == null || acl.isBlank()) {
return false;
}
try {
S3AclPolicy policy = S3AclPolicy.parse(acl);
return policy.grants().stream().anyMatch(S3AclPolicy.Grant::allowsPublicRead);
} catch (S3AclPolicy.AclParseException e) {
LOG.debugv(e, "Failed to parse S3 ACL for public read evaluation");
return false;
}
}
}
@@ -163,8 +163,13 @@ public class S3Controller {
@HEAD
@Path("/{bucket}")
public Response headBucket(@PathParam("bucket") String bucket) {
public Response headBucket(@PathParam("bucket") String bucket,
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeaders) {
try {
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
s3Service.authorizeBucketRead(bucket, "s3:ListBucket", authorization);
s3Service.headBucket(bucket);
String bucketRegion = s3Service.getBucketRegion(bucket);
if (bucketRegion == null || bucketRegion.isBlank()) {
@@ -333,60 +338,79 @@ public class S3Controller {
@Context HttpHeaders httpHeaders) {
try {
validateRawUri();
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
if (hasQueryParam(uriInfo, "uploads")) {
s3Service.authorizeBucketRead(bucket, "s3:ListBucketMultipartUploads", authorization);
return handleListMultipartUploads(bucket);
}
if (hasQueryParam(uriInfo, "notification")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketNotification", authorization);
return handleGetBucketNotification(bucket);
}
if (hasQueryParam(uriInfo, "versioning")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketVersioning", authorization);
return handleGetBucketVersioning(bucket);
}
if (hasQueryParam(uriInfo, "versions")) {
s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization);
return handleListObjectVersions(bucket, prefix, maxKeys, keyMarker);
}
if (hasQueryParam(uriInfo, "location")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization);
return handleGetBucketLocation(bucket);
}
if (hasQueryParam(uriInfo, "tagging")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketTagging", authorization);
return handleGetBucketTagging(bucket);
}
if (hasQueryParam(uriInfo, "object-lock")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketObjectLockConfiguration", authorization);
return handleGetObjectLockConfiguration(bucket);
}
if (hasQueryParam(uriInfo, "website")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketWebsite", authorization);
return handleGetBucketWebsite(bucket);
}
if (hasQueryParam(uriInfo, "logging")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketLogging", authorization);
return Response.ok(s3Service.getBucketLogging(bucket))
.type("application/xml")
.build();
}
if (hasQueryParam(uriInfo, "policy")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketPolicy", authorization);
return Response.ok(s3Service.getBucketPolicy(bucket)).build();
}
if (hasQueryParam(uriInfo, "cors")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketCORS", authorization);
return Response.ok(s3Service.getBucketCors(bucket)).build();
}
if (hasQueryParam(uriInfo, "lifecycle")) {
s3Service.authorizeBucketRead(bucket, "s3:GetLifecycleConfiguration", authorization);
S3Service.LifecycleConfigurationResult lc = s3Service.getBucketLifecycle(bucket);
return Response.ok(lc.xml())
.header("x-amz-transition-default-minimum-object-size", lc.transitionDefaultMinimumObjectSize())
.build();
}
if (hasQueryParam(uriInfo, "acl")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketAcl", authorization);
return Response.ok(s3Service.getBucketAcl(bucket)).build();
}
if (hasQueryParam(uriInfo, "encryption")) {
s3Service.authorizeBucketRead(bucket, "s3:GetEncryptionConfiguration", authorization);
return Response.ok(s3Service.getBucketEncryption(bucket)).build();
}
if (hasQueryParam(uriInfo, "publicAccessBlock")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketPublicAccessBlock", authorization);
return Response.ok(s3Service.getPublicAccessBlock(bucket)).build();
}
if (hasQueryParam(uriInfo, "ownershipControls")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketOwnershipControls", authorization);
return Response.ok(s3Service.getBucketOwnershipControls(bucket)).build();
}
if (hasQueryParam(uriInfo, "requestPayment")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketRequestPayment", authorization);
return Response.ok(s3Service.getBucketRequestPayment(bucket)).build();
}
@@ -396,6 +420,7 @@ public class S3Controller {
WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);
if (webConfig.getIndexDocument() != null) {
try {
s3Service.authorizeGetObject(bucket, webConfig.getIndexDocument(), null, authorization);
S3Object indexObj = s3Service.getObject(bucket, webConfig.getIndexDocument());
return Response.ok(indexObj.getData())
.type(indexObj.getContentType())
@@ -404,15 +429,25 @@ public class S3Controller {
.header("x-amz-website-redirect-location", "index")
.build();
} catch (AwsException e) {
Response r = serveErrorDocument(bucket, webConfig);
if (r != null) return r;
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
Response r = serveErrorDocument(bucket, webConfig, authorization, e.getHttpStatus());
if (r != null) {
return r;
}
}
}
} catch (AwsException e) {
if (!"NoSuchWebsiteConfiguration".equals(e.getErrorCode())) {
throw e;
}
// Bucket is not a website, continue to listObjects
}
}
s3Service.authorizeListBucket(bucket, authorization);
int max = (maxKeys != null && maxKeys > 0) ? maxKeys : 1000;
boolean v1 = !"2".equals(listType);
String effectiveStartAfter = v1 && marker != null ? marker : startAfter;
@@ -605,31 +640,42 @@ public class S3Controller {
@HeaderParam("Range") String rangeHeader,
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeaders) {
S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned();
try {
key = extractObjectKey(uriInfo, bucket);
authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
if (uploadId != null) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:ListMultipartUploadParts", authorization);
return handleListParts(bucket, key, uploadId, maxPartsQuery, partNumberMarkerQuery);
}
if (hasQueryParam(uriInfo, "tagging")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectTagging", authorization);
return handleGetObjectTagging(bucket, key);
}
if (hasQueryParam(uriInfo, "retention")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectRetention", authorization);
return handleGetObjectRetention(bucket, key, versionId);
}
if (hasQueryParam(uriInfo, "legal-hold")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectLegalHold", authorization);
return handleGetObjectLegalHold(bucket, key, versionId);
}
if (hasQueryParam(uriInfo, "acl")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAcl", authorization);
return Response.ok(s3Service.getObjectAcl(bucket, key, versionId)).build();
}
if (hasQueryParam(uriInfo, "attributes")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAttributes", authorization);
// Merge all x-amz-object-attributes header values (SDK may send multiple lines)
List<String> attrHeaders = httpHeaders.getRequestHeader("x-amz-object-attributes");
String mergedAttributes = attrHeaders != null ? String.join(",", attrHeaders) : objectAttributesHeader;
return handleGetObjectAttributes(bucket, key, versionId,
mergedAttributes, maxParts, partNumberMarker);
}
s3Service.authorizeGetObject(bucket, key, versionId, authorization);
if (hasPreconditions(ifMatch, ifNoneMatch, ifModifiedSince, ifUnmodifiedSince)) {
// Fetch metadata only to evaluate preconditions, avoiding loading the full object unnecessarily.
S3Object metadata = s3Service.headObject(bucket, key, versionId);
@@ -647,7 +693,7 @@ public class S3Controller {
ResponseHeaderOverrides overrides = new ResponseHeaderOverrides(
responseContentType, responseContentLanguage, responseExpires,
responseCacheControl, responseContentDisposition, responseContentEncoding);
if (overrides.hasAny() && !isSigned(httpHeaders, uriInfo)) {
if (overrides.hasAny() && !S3RequestAuthorizationParser.isSigned(httpHeaders, uriInfo)) {
return xmlErrorResponse(new AwsException("InvalidRequest",
"Request specific response headers cannot be used for anonymous GET requests.", 400));
}
@@ -658,12 +704,17 @@ public class S3Controller {
return fullObjectResponse(bucket, key, versionId, obj, overrides);
} catch (AwsException e) {
if ("NoSuchKey".equals(e.getErrorCode()) && isWebsiteRequest(httpHeaders)) {
if (isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders)) {
try {
WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);
Response r = serveErrorDocument(bucket, webConfig);
if (r != null) return r;
} catch (AwsException ignored) {
Response r = serveErrorDocument(bucket, webConfig, authorization, e.getHttpStatus());
if (r != null) {
return r;
}
} catch (AwsException websiteException) {
if (!"NoSuchWebsiteConfiguration".equals(websiteException.getErrorCode())) {
return xmlErrorResponse(websiteException);
}
}
}
return xmlErrorResponse(e);
@@ -801,6 +852,10 @@ public class S3Controller {
@Context HttpHeaders httpHeaders) {
try {
key = extractObjectKey(uriInfo, bucket);
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
s3Service.authorizeGetObject(bucket, key, versionId, authorization);
S3Object obj = s3Service.headObject(bucket, key, versionId);
S3Service.validateSseCustomerAccess(
obj,
@@ -814,7 +869,7 @@ public class S3Controller {
ResponseHeaderOverrides overrides = new ResponseHeaderOverrides(
responseContentType, responseContentLanguage, responseExpires,
responseCacheControl, responseContentDisposition, responseContentEncoding);
if (overrides.hasAny() && !isSigned(httpHeaders, uriInfo)) {
if (overrides.hasAny() && !S3RequestAuthorizationParser.isSigned(httpHeaders, uriInfo)) {
return xmlErrorResponse(new AwsException("InvalidRequest",
"Request specific response headers cannot be used for anonymous GET requests.", 400));
}
@@ -1010,6 +1065,9 @@ public class S3Controller {
}
if (hasQueryParam(uriInfo, "select")) {
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
s3Service.authorizeGetObject(bucket, key, versionId, authorization);
S3Object obj = s3Service.getObject(bucket, key, versionId);
byte[] result = s3SelectService.select(obj, new String(body, StandardCharsets.UTF_8));
return Response.ok(result)
@@ -2035,29 +2093,56 @@ public class S3Controller {
return host != null && host.contains("s3-website");
}
private Response serveErrorDocument(String bucket, WebsiteConfiguration cfg) {
private Response serveErrorDocument(String bucket, WebsiteConfiguration cfg,
S3Service.RequestAuthorization authorization, int status) {
if (cfg.getErrorDocument() == null) {
return null;
}
int responseStatus = status == 403 ? 403 : 404;
try {
s3Service.authorizeGetObject(bucket, cfg.getErrorDocument(), null, authorization);
S3Object err = s3Service.getObject(bucket, cfg.getErrorDocument());
return Response.status(404)
return Response.status(responseStatus)
.entity(err.getData())
.type(err.getContentType())
.header("Content-Length", err.getSize())
.header("x-amz-error-code", "NoSuchKey")
.header("x-amz-error-message", "The specified key does not exist.")
.header("x-amz-error-code", websiteErrorCode(responseStatus))
.header("x-amz-error-message", websiteErrorMessage(responseStatus))
.build();
} catch (AwsException ignored) {
return Response.status(404)
.entity("<html><head><title>404 Not Found</title></head>\n<body><h1>404 Not Found</h1>\n<ul><li>Code: NoSuchKey</li><li>Message: The specified key does not exist.</li></ul></body></html>")
} catch (AwsException e) {
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
return Response.status(responseStatus)
.entity(defaultWebsiteErrorBody(responseStatus))
.type(MediaType.TEXT_HTML)
.header("x-amz-error-code", "NoSuchKey")
.header("x-amz-error-message", "The specified key does not exist.")
.header("x-amz-error-code", websiteErrorCode(responseStatus))
.header("x-amz-error-message", websiteErrorMessage(responseStatus))
.build();
}
}
private static boolean isWebsiteErrorDocumentTrigger(AwsException e) {
return "NoSuchKey".equals(e.getErrorCode()) || "AccessDenied".equals(e.getErrorCode());
}
private static String websiteErrorCode(int status) {
return status == 403 ? "AccessDenied" : "NoSuchKey";
}
private static String websiteErrorMessage(int status) {
return status == 403 ? "Access Denied" : "The specified key does not exist.";
}
private static String defaultWebsiteErrorBody(int status) {
String title = status + (status == 403 ? " Forbidden" : " Not Found");
String code = websiteErrorCode(status);
String message = websiteErrorMessage(status);
return "<html><head><title>" + title + "</title></head>\n"
+ "<body><h1>" + title + "</h1>\n"
+ "<ul><li>Code: " + code + "</li><li>Message: " + message + "</li></ul></body></html>";
}
private Response xmlErrorResponse(AwsException e) {
String condition = e instanceof S3PreconditionFailedException preconditionFailedException
? preconditionFailedException.condition()
@@ -2138,13 +2223,8 @@ public class S3Controller {
return null;
}
private static boolean isSigned(HttpHeaders httpHeaders, UriInfo uriInfo) {
return httpHeaders.getHeaderString("Authorization") != null
|| uriInfo.getQueryParameters().containsKey("X-Amz-Algorithm");
}
private boolean hasPreconditions(String ifMatch, String ifNoneMatch,
String ifModifiedSince, String ifUnmodifiedSince) {
String ifModifiedSince, String ifUnmodifiedSince) {
return ifMatch != null || ifNoneMatch != null || ifModifiedSince != null || ifUnmodifiedSince != null;
}
@@ -0,0 +1,182 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import org.jboss.logging.Logger;
import java.util.Iterator;
import java.util.List;
final class S3PublicAccessEvaluator {
private static final Logger LOG = Logger.getLogger(S3PublicAccessEvaluator.class);
enum PublicAccessDecision {
ALLOW,
DENY,
NEUTRAL
}
private S3PublicAccessEvaluator() {
}
static boolean publicPolicyAllows(ObjectMapper objectMapper, String policy, String action, String resourceArn) {
return publicPolicyDecision(objectMapper, policy, action, resourceArn) == PublicAccessDecision.ALLOW;
}
static PublicAccessDecision publicPolicyDecision(ObjectMapper objectMapper, String policy, String action, String resourceArn) {
if (policy == null || policy.isBlank()) {
return PublicAccessDecision.NEUTRAL;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
boolean allowed = false;
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
String effect = statement.path("Effect").asText("");
if (!"Allow".equalsIgnoreCase(effect) && !"Deny".equalsIgnoreCase(effect)) {
continue;
}
if (!statementMatchesPublicPrincipalActionResource(statement, action, resourceArn)) {
continue;
}
if ("Deny".equalsIgnoreCase(effect)) {
return PublicAccessDecision.DENY;
}
if (statement.hasNonNull("Condition")) {
continue;
}
allowed = true;
}
return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
} catch (JsonProcessingException e) {
LOG.debugv("Failed to evaluate S3 bucket policy for public access: {0}", e.getMessage());
return PublicAccessDecision.NEUTRAL;
}
}
static String bucketArn(String bucketName) {
return "arn:aws:s3:::" + bucketName;
}
static String objectArn(String bucketName, String key) {
return bucketArn(bucketName) + "/" + key;
}
private static boolean statementMatchesPublicPrincipalActionResource(JsonNode statement, String action, String resourceArn) {
return principalMatchesPublic(statement)
&& actionMatches(statement, action)
&& resourceMatches(statement, resourceArn);
}
private static boolean principalMatchesPublic(JsonNode statement) {
if (statement.hasNonNull("Principal")) {
return hasPublicPrincipal(statement.path("Principal"));
}
if (statement.hasNonNull("NotPrincipal")) {
return !hasPublicPrincipal(statement.path("NotPrincipal"));
}
return false;
}
private static boolean actionMatches(JsonNode statement, String action) {
if (statement.hasNonNull("Action")) {
return nodeMatches(statement.get("Action"), action);
}
if (statement.hasNonNull("NotAction")) {
JsonNode notAction = statement.get("NotAction");
return nodeCanMatch(notAction) && !nodeMatches(notAction, action);
}
return false;
}
private static boolean resourceMatches(JsonNode statement, String resourceArn) {
if (statement.hasNonNull("Resource")) {
return nodeMatches(statement.get("Resource"), resourceArn);
}
if (statement.hasNonNull("NotResource")) {
JsonNode notResource = statement.get("NotResource");
return nodeCanMatch(notResource) && !nodeMatches(notResource, resourceArn);
}
return false;
}
private static boolean hasPublicPrincipal(JsonNode principal) {
if (principal == null || principal.isMissingNode() || principal.isNull()) {
return false;
}
if (principal.isTextual()) {
return "*".equals(principal.asText());
}
if (principal.isArray()) {
for (JsonNode item : principal) {
if ("*".equals(item.asText())) {
return true;
}
}
return false;
}
if (principal.isObject()) {
Iterator<JsonNode> values = principal.elements();
while (values.hasNext()) {
if (nodeContainsPublicPrincipal(values.next())) {
return true;
}
}
}
return false;
}
private static boolean nodeContainsPublicPrincipal(JsonNode node) {
if (node == null || node.isNull()) {
return false;
}
if (node.isTextual()) {
return "*".equals(node.asText());
}
if (node.isArray()) {
for (JsonNode item : node) {
if ("*".equals(item.asText())) {
return true;
}
}
}
return false;
}
private static boolean nodeCanMatch(JsonNode node) {
if (node == null || node.isNull()) {
return false;
}
if (node.isTextual()) {
return true;
}
if (node.isArray()) {
for (JsonNode item : node) {
if (item.isTextual()) {
return true;
}
}
}
return false;
}
private static boolean nodeMatches(JsonNode node, String value) {
if (node == null || node.isNull()) {
return false;
}
if (node.isTextual()) {
return IamPolicyEvaluator.globMatches(node.asText(), value);
}
if (node.isArray()) {
for (JsonNode item : node) {
if (item.isTextual() && IamPolicyEvaluator.globMatches(item.asText(), value)) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
final class S3RequestAuthorizationParser {
private static final String SIGV4_ALGORITHM = "AWS4-HMAC-SHA256";
static final String AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE = "AuthorizationQueryParametersError";
static final String AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE =
"Query-string authentication version 4 requires the X-Amz-Algorithm, "
+ "X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, "
+ "and X-Amz-Expires parameters.";
static final int AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS = 400;
private static final Set<String> REQUIRED_PRESIGNED_PARAMETERS = Set.of(
"X-Amz-Algorithm",
"X-Amz-Credential",
"X-Amz-Date",
"X-Amz-Expires",
"X-Amz-SignedHeaders",
"X-Amz-Signature");
private S3RequestAuthorizationParser() {
}
static boolean isSigned(HttpHeaders httpHeaders, UriInfo uriInfo) {
return isSigned(httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters());
}
static boolean isSigned(String authorization, MultivaluedMap<String, String> queryParameters) {
return (authorization != null && !authorization.isBlank())
|| queryParameters.containsKey("X-Amz-Algorithm");
}
static S3Service.RequestAuthorization parseIfRequired(
boolean enforceAuth, HttpHeaders httpHeaders, UriInfo uriInfo) {
if (!enforceAuth) {
return S3Service.RequestAuthorization.unsigned();
}
return parse(httpHeaders, uriInfo);
}
static S3Service.RequestAuthorization parseIfRequired(
boolean enforceAuth, String authorization, MultivaluedMap<String, String> queryParameters) {
if (!enforceAuth) {
return S3Service.RequestAuthorization.unsigned();
}
return parse(authorization, queryParameters);
}
static S3Service.RequestAuthorization parse(HttpHeaders httpHeaders, UriInfo uriInfo) {
return parse(httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters());
}
static S3Service.RequestAuthorization parse(String authorization, MultivaluedMap<String, String> queryParameters) {
if (authorization != null && !authorization.isBlank()) {
String accessKeyId = extractAuthorizationHeaderAccessKeyId(authorization);
if (accessKeyId == null) {
// Only SigV4 is parsed; unsupported schemes are reported as malformed auth.
String message = "The authorization header is malformed; the credential scope is invalid.";
throw new AwsException("AuthorizationHeaderMalformed", message, 400);
}
return new S3Service.RequestAuthorization(true, accessKeyId);
}
if (queryParameters.containsKey("X-Amz-Algorithm")) {
String accessKeyId = extractPresignedAccessKeyId(queryParameters);
if (accessKeyId == null) {
throw new AwsException(AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE,
AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE,
AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS);
}
return new S3Service.RequestAuthorization(true, accessKeyId);
}
return S3Service.RequestAuthorization.unsigned();
}
private static String extractAuthorizationHeaderAccessKeyId(String authorization) {
String trimmed = authorization.trim();
if (!trimmed.startsWith(SIGV4_ALGORITHM + " ")) {
return null;
}
Map<String, String> parameters = authorizationParameters(trimmed.substring(SIGV4_ALGORITHM.length()).trim());
if (isBlank(parameters.get("SignedHeaders")) || isBlank(parameters.get("Signature"))) {
return null;
}
return extractCredentialAccessKeyId(parameters.get("Credential"));
}
private static String extractPresignedAccessKeyId(MultivaluedMap<String, String> queryParameters) {
if (!SIGV4_ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"))) {
return null;
}
if (isMissingRequiredPresignedParameter(queryParameters)) {
return null;
}
return extractCredentialAccessKeyId(queryParameters.getFirst("X-Amz-Credential"));
}
static boolean isMissingRequiredPresignedParameter(MultivaluedMap<String, String> queryParameters) {
for (String parameter : REQUIRED_PRESIGNED_PARAMETERS) {
if (isBlank(queryParameters.getFirst(parameter))) {
return true;
}
}
return false;
}
private static Map<String, String> authorizationParameters(String parameters) {
Map<String, String> parsed = new LinkedHashMap<>();
for (String part : parameters.split(",")) {
int equals = part.indexOf('=');
if (equals <= 0) {
continue;
}
parsed.put(part.substring(0, equals).trim(), part.substring(equals + 1).trim());
}
return parsed;
}
private static String extractCredentialAccessKeyId(String credential) {
if (isBlank(credential)) {
return null;
}
String[] parts = credential.split("/", -1);
if (parts.length != 5) {
return null;
}
if (parts[0].isBlank() || !isEightDigitDate(parts[1]) || parts[2].isBlank()) {
return null;
}
if (!"s3".equals(parts[3]) || !"aws4_request".equals(parts[4])) {
return null;
}
return parts[0];
}
private static boolean isEightDigitDate(String value) {
if (value.length() != 8) {
return false;
}
for (int index = 0; index < value.length(); index++) {
if (!Character.isDigit(value.charAt(index))) {
return false;
}
}
return true;
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
}
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.s3.model.*;
@@ -44,8 +45,8 @@ import java.util.concurrent.ConcurrentHashMap;
public class S3Service implements Resettable {
private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }
private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";
private static final String ALL_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AllUsers";
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
private static final String LEGACY_ACCESS_KEY_ID = "test";
private static final Set<String> SUPPORTED_SERVER_SIDE_ENCRYPTION_VALUES = Set.of("AES256", "aws:kms", "aws:kms:dsse", "aws:fsx");
private static final String SSE_C_ALGORITHM = "AES256";
private static final int SSE_C_KEY_BYTES = 32;
@@ -57,6 +58,12 @@ public class S3Service implements Resettable {
private static final Logger LOG = Logger.getLogger(S3Service.class);
record RequestAuthorization(boolean signed, String accessKeyId) {
static RequestAuthorization unsigned() {
return new RequestAuthorization(false, null);
}
}
private final StorageBackend<String, Bucket> bucketStore;
private final StorageBackend<String, S3Object> objectStore;
private final Path dataRoot;
@@ -75,6 +82,8 @@ public class S3Service implements Resettable {
private final RegionResolver regionResolver;
private final String baseUrl;
private final ObjectMapper objectMapper;
private final boolean enforceAuth;
private final IamService iamService;
@Inject
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
@@ -83,7 +92,8 @@ public class S3Service implements Resettable {
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
IamService iamService) {
this(
storageFactory.create("s3", "s3-buckets.json",
new TypeReference<Map<String, Bucket>>() {
@@ -96,7 +106,8 @@ public class S3Service implements Resettable {
sqsService, snsService, null, lambdaServiceProvider, null,
eventBridgeService, s3UpdatedEvent,
regionResolver,
config.effectiveBaseUrl(), objectMapper
config.effectiveBaseUrl(), objectMapper,
config.services().s3().enforceAuth(), iamService
);
}
@@ -107,7 +118,7 @@ public class S3Service implements Resettable {
StorageBackend<String, S3Object> objectStore,
Path dataRoot, boolean inMemory) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper());
null, "http://localhost:4566", new ObjectMapper(), false, null);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -116,7 +127,7 @@ public class S3Service implements Resettable {
LambdaService lambdaService,
RegionResolver regionResolver) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, lambdaService, null, null, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper());
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -125,7 +136,7 @@ public class S3Service implements Resettable {
LambdaInvoker lambdaInvoker,
RegionResolver regionResolver) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, lambdaInvoker, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper());
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);
}
private S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -136,7 +147,8 @@ public class S3Service implements Resettable {
LambdaInvoker lambdaInvoker,
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper) {
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
boolean enforceAuth, IamService iamService) {
this.bucketStore = bucketStore;
this.objectStore = objectStore;
this.dataRoot = dataRoot;
@@ -151,6 +163,8 @@ public class S3Service implements Resettable {
this.regionResolver = regionResolver;
this.baseUrl = baseUrl;
this.objectMapper = objectMapper;
this.enforceAuth = enforceAuth;
this.iamService = iamService;
if (!inMemory) {
try {
Files.createDirectories(dataRoot);
@@ -458,6 +472,115 @@ public class S3Service implements Resettable {
return normalized;
}
public void authorizeListBucket(String bucketName, RequestAuthorization authorization) {
authorizeBucketRead(bucketName, "s3:ListBucket", authorization);
}
public void authorizeGetObject(String bucketName, String key, String versionId, RequestAuthorization authorization) {
String action = versionId != null ? "s3:GetObjectVersion" : "s3:GetObject";
if (enforceAuth && versionId == null && isUnsignedRequest(authorization) && !readableObjectExists(bucketName, key)) {
authorizeMissingObjectRead(bucketName, authorization);
return;
}
authorizeObjectRead(bucketName, key, versionId, action, authorization);
}
void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) {
String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);
}
void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) {
String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);
authorizeS3Read(bucketName, key, versionId, action, objectArn, authorization);
}
boolean isAuthEnforced() {
return enforceAuth;
}
private void authorizeS3Read(String bucketName, String key, String versionId, String action, String resourceArn, RequestAuthorization authorization) {
if (!enforceAuth) {
return;
}
RequestAuthorization requestAuthorization = authorization != null
? authorization
: RequestAuthorization.unsigned();
if (requestAuthorization.signed()) {
if (isKnownAccessKey(requestAuthorization.accessKeyId())) {
return;
}
throw new AwsException("InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records.", 403);
}
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
S3PublicAccessEvaluator.PublicAccessDecision policyDecision =
S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, resourceArn);
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {
throw new AwsException("AccessDenied", "Access Denied", 403);
}
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {
return;
}
if (key != null && isObjectDataReadAction(action) && publicObjectAclAllowsRead(bucketName, key, versionId)) {
return;
}
if (key == null && "s3:ListBucket".equals(action) && publicBucketAclAllowsRead(bucket)) {
return;
}
throw new AwsException("AccessDenied", "Access Denied", 403);
}
private boolean readableObjectExists(String bucketName, String key) {
ensureBucketExists(bucketName);
return objectStore.get(objectKey(bucketName, key))
.filter(object -> !object.isDeleteMarker())
.isPresent();
}
private void authorizeMissingObjectRead(String bucketName, RequestAuthorization authorization) {
authorizeListBucket(bucketName, authorization);
}
private static boolean isObjectDataReadAction(String action) {
return "s3:GetObject".equals(action) || "s3:GetObjectVersion".equals(action);
}
private static boolean isUnsignedRequest(RequestAuthorization authorization) {
return authorization == null || !authorization.signed();
}
private boolean isKnownAccessKey(String accessKeyId) {
if (accessKeyId == null || accessKeyId.isBlank()) {
return false;
}
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
return true;
}
return iamService != null && iamService.findSecretKey(accessKeyId).isPresent();
}
private boolean publicBucketAclAllowsRead(Bucket bucket) {
return Optional.ofNullable(bucket.getAcl())
.map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)
.orElse(false);
}
private boolean publicObjectAclAllowsRead(String bucketName, String key, String versionId) {
String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
return objectStore.get(storeKey)
.filter(object -> !object.isDeleteMarker())
.map(S3Object::getAcl)
.map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)
.orElse(false);
}
private void applyObjectLock(S3Object object, Bucket bucket,
String objectLockMode, Instant retainUntilDate, String legalHoldStatus) {
if (objectLockMode != null) {
@@ -1784,11 +1907,11 @@ public class S3Service implements Resettable {
case "aws-exec-read" -> defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
case "public-read" -> objectAclXml(
ownerFullControlGrant(),
groupGrant(ALL_USERS_GROUP_URI, "READ"));
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"));
case "public-read-write" -> objectAclXml(
ownerFullControlGrant(),
groupGrant(ALL_USERS_GROUP_URI, "READ"),
groupGrant(ALL_USERS_GROUP_URI, "WRITE"));
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"),
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE"));
case "authenticated-read" -> objectAclXml(
ownerFullControlGrant(),
groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"));