Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): check the actions an S3 operation needs besides its own (#5846)
Priamo Germosenb0777a402069
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex a4b958ff06..0443097fa1 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -1153,14 +1153,34 @@ An S3 object operation is checked as the action the S3 documentation gives it:`s3:PutObject`.- `AbortMultipartUpload` is checked as `s3:AbortMultipartUpload`.- `ListParts` is checked as `s3:ListMultipartUploadParts`.+- **Creating an object:** a `PutObject`, `CopyObject` or `CreateMultipartUpload` also needs+ the action for each setting it applies to the new object, as the S3 user guide's permissions+ table marks them conditionally required:+ - `s3:PutObjectTagging` for tags: the `x-amz-tagging` header, which a copy applies only with+ `x-amz-tagging-directive: REPLACE`, or a tagged source's tags, which a copy keeps under the+ default `COPY`;+ - `s3:PutObjectAcl` for a canned ACL or a grant header;+ - `s3:PutObjectRetention` for `x-amz-object-lock-mode` or `x-amz-object-lock-retain-until-date`;+ - `s3:PutObjectLegalHold` for `x-amz-object-lock-legal-hold`.++ S3's own access check under `floci.services.s3.enforce-auth`, which evaluates bucket policies+ and ACLs, checks only `s3:PutObject` for these operations.- **Restore and select:** `RestoreObject` is checked as `s3:RestoreObject`, and`SelectObjectContent` as `s3:GetObject`, or `s3:GetObjectVersion` when it names a version.-- **Object lock:** object retention and legal hold use their own actions: `s3:GetObjectRetention`,- `s3:PutObjectRetention`, `s3:GetObjectLegalHold` and `s3:PutObjectLegalHold`.+- **Attributes:** `GetObjectAttributes` needs `s3:GetObject` and `s3:GetObjectAttributes`, as its+ API reference says.+- **Object lock:**+ - Object retention and legal hold use their own actions: `s3:GetObjectRetention`,+ `s3:PutObjectRetention`, `s3:GetObjectLegalHold` and `s3:PutObjectLegalHold`.+ - A `PutObjectRetention` or `DeleteObject` that sends `x-amz-bypass-governance-retention: true`+ also needs `s3:BypassGovernanceRetention`, as their API references say. The S3 user guide says+ the permission does not apply to annotation operations, so deleting an annotation does not+ need it.- **Annotations:** object annotations use the `s3:*ObjectAnnotation` actions, and`s3:ListObjectAnnotations` when no annotation name is given.- **Versions:** a `versionId` selects the version action AWS checks.- - Reading or heading a version needs `s3:GetObjectVersion`; `s3:GetObject` is not needed.+ - Reading or heading a version needs `s3:GetObjectVersion`; `s3:GetObject` is not needed. Its+ attributes need `s3:GetObjectVersion` and `s3:GetObjectVersionAttributes`.- Deleting a version needs `s3:DeleteObjectVersion`, so a deny on it stops permanent deleteswhile a plain delete still adds a delete marker.- A version's ACL, tags and annotations use `s3:GetObjectVersionAcl`, `s3:PutObjectVersionAcl`,@@ -1498,7 +1518,9 @@ floci populates:be gated on tags an object does not have yet.- `s3:RequestObjectTag/<key>`: a tag the request asks to attach. `s3:PutObject` reads thesefrom the `x-amz-tagging` header, or its query parameter when the header is absent,- and `s3:PutObjectTagging` from the `<Tagging>` body. Any pair+ and `s3:PutObjectTagging` from the `<Tagging>` body. A `CopyObject` offers them only with+ `x-amz-tagging-directive: REPLACE`: under the default `COPY` the copy keeps the source's tags and+ ignores the header. Any pairthat does not decode is dropped, so a policy conditioned on the key denies such a request. Whereenforcement lets it through, the handler still answers a malformed header with`400 InvalidTag`.@@ -1509,6 +1531,15 @@ floci populates:omitted or empty tag set still follows the absent-key rules above. Existing object tagsdo not contribute to this requested set. See the [AWS object-tag policy guidance](https://docs.aws.amazon.com/AmazonS3/latest/userguide/tagging-and-policies.html).- `s3:versionid`: the `versionId` of the request, for the version actions it selects.+- `s3:object-lock-mode`, `s3:object-lock-retain-until-date`,+ `s3:object-lock-remaining-retention-days` and `s3:object-lock-legal-hold`: the Object Lock+ settings a request applies, for `s3:PutObject` (from its `x-amz-object-lock-*` headers),+ `s3:PutObjectRetention` (the `<Retention>` body) and `s3:PutObjectLegalHold` (the `<LegalHold>`+ body). AWS does not document how it counts the remaining retention days; floci counts a part+ day as a whole one, so a Deny on retention longer than N days refuses a date a few hours past+ N days.+- An object creation offers its tag and Object Lock keys to each action it is checked as: its+ `s3:PutObject` and the extra actions its settings need.- A `PutObject` carrying `If-Match` is authorized as `s3:GetObject` as well, and that secondcheck is made without the object's tags in the context, as measured on AWS. `CopyObject` and`CompleteMultipartUpload`, the other operations the S3 user guide lists for `If-Match`, get thediff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.javaindex 4fbadbc182..ddf87d7280 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java@@ -28,6 +28,7 @@ import java.io.InputStream;import java.net.URLDecoder;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;+import java.time.Clock;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.LinkedHashSet;@@ -70,6 +71,10 @@ public class IamConditionContextResolver {public static final String REQUEST_OBJECT_TAG_PREFIX = "s3:RequestObjectTag/";public static final String REQUEST_OBJECT_TAG_KEYS = "s3:RequestObjectTagKeys";public static final String VERSION_ID = "s3:versionid";+ public static final String OBJECT_LOCK_MODE = "s3:object-lock-mode";+ public static final String OBJECT_LOCK_RETAIN_UNTIL_DATE = "s3:object-lock-retain-until-date";+ public static final String OBJECT_LOCK_REMAINING_RETENTION_DAYS = "s3:object-lock-remaining-retention-days";+ public static final String OBJECT_LOCK_LEGAL_HOLD = "s3:object-lock-legal-hold";private final Instance<DynamoDbFacade> dynamoDbFacade;private final Instance<Ec2Service> ec2Service;@@ -77,7 +82,12 @@ public class IamConditionContextResolver {private final Instance<CloudWatchLogsService> logsService;private final RequestContext requestContext;private final EmulatorConfig config;+ private final Clock clock;+ /**+ * The system clock, not the CDI one: Object Lock's remaining retention days has to count from the+ * same now as S3Service, which checks retention against {@code Instant.now()}.+ */@Injectpublic IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,Instance<Ec2Service> ec2Service,@@ -85,12 +95,23 @@ public class IamConditionContextResolver {Instance<CloudWatchLogsService> logsService,RequestContext requestContext,EmulatorConfig config) {+ this(dynamoDbFacade, ec2Service, s3Service, logsService, requestContext, config, Clock.systemUTC());+ }++ IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,+ Instance<Ec2Service> ec2Service,+ Instance<S3Service> s3Service,+ Instance<CloudWatchLogsService> logsService,+ RequestContext requestContext,+ EmulatorConfig config,+ Clock clock) {this.dynamoDbFacade = dynamoDbFacade;this.ec2Service = ec2Service;this.s3Service = s3Service;this.logsService = logsService;this.requestContext = requestContext;this.config = config;+ this.clock = clock;}public Map<String, List<String>> resolve(String credentialScope, String action,@@ -290,13 +311,28 @@ public class IamConditionContextResolver {"s3:ListObjectAnnotations", "s3:ListObjectVersionAnnotations", "s3:PutObjectAnnotation","s3:PutObjectVersionAnnotation", "s3:DeleteObjectAnnotation","s3:DeleteObjectVersionAnnotation" -> s3ExistingObjectTagConditionContext(ctx);- case "s3:PutObject" -> s3RequestObjectTagConditionContext(ctx);+ // The Object Lock keys come from what the request sets: an object creation's headers, the+ // retention and legal-hold bodies.+ case "s3:PutObject" -> S3ObjectActions.objectCreationConditions(+ ctx::getHeaderString, s3RequestTagging(ctx), clock.instant());+ case "s3:PutObjectRetention" -> {+ String body = bodyText(ctx);+ yield S3ObjectActions.objectLockConditions(XmlParser.extractFirst(body, "Mode", null),+ XmlParser.extractFirst(body, "RetainUntilDate", null), null, clock.instant());+ }+ case "s3:PutObjectLegalHold" -> S3ObjectActions.objectLockConditions(null, null,+ XmlParser.extractFirst(bodyText(ctx), "Status", null), clock.instant());case "s3:PutObjectTagging", "s3:PutObjectVersionTagging" -> merge(s3ExistingObjectTagConditionContext(ctx), s3PutObjectTaggingBodyConditionContext(ctx));default -> null;};}+ private static String bodyText(ContainerRequestContext ctx) {+ byte[] body = bufferEntity(ctx);+ return body == null ? null : new String(body, StandardCharsets.UTF_8);+ }+/*** {@code s3:ExistingObjectTag/<key>} from the tags of the version this request targets. An* object that does not exist, or has no tags, offers no keys, so a {@code StringEquals} on one@@ -334,37 +370,16 @@ public class IamConditionContextResolver {}/**- * {@code s3:RequestObjectTag/<key>} from a PutObject's {@code x-amz-tagging} header, or the- * query parameter where a presigner may place it. The header takes precedence, including- * an empty header, matching the source the S3 controller applies to the object.+ * A PutObject's {@code x-amz-tagging}: the header, or the query parameter where a presigner may+ * place it. The header takes precedence, including an empty header, matching the source the S3+ * controller applies to the object.*/- private Map<String, List<String>> s3RequestObjectTagConditionContext(ContainerRequestContext ctx) {+ private static String s3RequestTagging(ContainerRequestContext ctx) {String header = ctx.getHeaderString("x-amz-tagging");if (header == null && ctx.getUriInfo() != null) {header = ctx.getUriInfo().getQueryParameters().getFirst("x-amz-tagging");}- if (header == null || header.isBlank()) {- return null;- }- Map<String, List<String>> conditions = new LinkedHashMap<>();- Set<String> requestedKeys = new LinkedHashSet<>();- for (String pair : header.split("&")) {- int eq = pair.indexOf('=');- if (eq <= 0) {- continue;- }- String name = urlDecode(pair.substring(0, eq));- String value = urlDecode(pair.substring(eq + 1));- if (name == null || value == null) {- continue;- }- conditions.put(REQUEST_OBJECT_TAG_PREFIX + name, List.of(value));- requestedKeys.add(name);- }- if (!requestedKeys.isEmpty()) {- conditions.put(REQUEST_OBJECT_TAG_KEYS, new ArrayList<>(requestedKeys));- }- return conditions.isEmpty() ? null : conditions;+ return header;}/** {@code s3:RequestObjectTag/<key>} from the {@code <Tagging>} XML body of PutObjectTagging. */@@ -396,21 +411,6 @@ public class IamConditionContextResolver {return merged;}- /**- * Null for a value {@code URLDecoder} refuses, such as the {@code %zz} of a malformed- * {@code x-amz-tagging} header. The caller drops the pair rather than letting the- * {@code IllegalArgumentException} out of the filter, where it becomes a 500 in place of the- * 400 {@code InvalidTag} the handler returns for the same header.- */- private static String urlDecode(String value) {- try {- return URLDecoder.decode(value, StandardCharsets.UTF_8);- } catch (IllegalArgumentException e) {- LOG.debugv(e, "Undecodable tag component in the IAM condition context: {0}", value);- return null;- }- }-/** The object key of a path-style (or filter-rewritten) S3 path, null for a bucket-level one. */private static String s3ObjectKey(String path) {String stripped = path.startsWith("/") ? path.substring(1) : path;diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 0de5a1bbfc..99a2f88f80 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;import io.github.hectorvent.floci.services.iam.ScpProvider;import io.github.hectorvent.floci.services.iam.model.CallerContext;+import io.github.hectorvent.floci.services.s3.S3ObjectActions;import io.quarkus.vertx.http.runtime.CurrentVertxRequest;import io.vertx.core.http.HttpServerRequest;import io.vertx.ext.web.RoutingContext;@@ -453,14 +454,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter {ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx));return;}- // A tagged PutObject additionally requires s3:PutObjectTagging. Generated URLs- // grant only their object operation (and GetObject for conditional writes), so- // an unsigned tagging header must not add permissions to the scoped session.- if ("s3:PutObject".equals(action)- && (ctx.getHeaderString("x-amz-tagging") != null- || ctx.getUriInfo().getQueryParameters().containsKey("x-amz-tagging"))) {- ctx.abortWith(accessDeniedForRequest("s3:PutObjectTagging", credentialScope, ctx));- return;+ // An object created with an ACL, tags, a retention period or a legal hold also needs+ // that setting's own action. Generated URLs grant only their object operation (and+ // GetObject for conditional writes), so such an unsigned header must not add+ // permissions to the scoped session.+ if ("s3:PutObject".equals(action) && isObjectCreation(ctx)) {+ List<String> creationActions =+ S3ObjectActions.objectCreationActions(ctx::getHeaderString, requestTagging(ctx));+ if (!creationActions.isEmpty()) {+ ctx.abortWith(accessDeniedForRequest(creationActions.getFirst(), credentialScope, ctx));+ return;+ }}}@@ -543,9 +547,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// permission. The user guide's conditional writes page lists PutObject, CopyObject and// CompleteMultipartUpload as the operations that take If-Match; CreateMultipartUpload and// UploadPart, also checked as s3:PutObject, ignore it, so it adds nothing to them.- if ("s3:PutObject".equals(action) && evaluatesIfMatch(ctx) && ctx.getHeaderString("If-Match") != null) {- abortIfDenied(ctx, caller, principal, "s3:GetObject", credentialScope, resources,- withoutObjectTags(targetContexts), region, accountId, akid);+ if ("s3:PutObject".equals(action) && evaluatesIfMatch(ctx) && ctx.getHeaderString("If-Match") != null+ && abortIfDenied(ctx, caller, principal, "s3:GetObject", action, credentialScope, resources,+ withoutObjectTags(targetContexts), region, accountId, akid)) {+ return;}// A DeleteObject conditioned on an ETag reveals whether the object still has it, and the// conditional-deletes guide requires s3:GetObject for it; If-Match: * (existence only)@@ -555,9 +560,44 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// PutObject case above is.if (("s3:DeleteObject".equals(action) || "s3:DeleteObjectVersion".equals(action))&& isPlainDeleteObject(ctx)- && isETagCondition(ctx.getHeaderString("If-Match"))) {- abortIfDenied(ctx, caller, principal, "s3:GetObject", credentialScope, resources,- withoutObjectTags(targetContexts), region, accountId, akid);+ && isETagCondition(ctx.getHeaderString("If-Match"))+ && abortIfDenied(ctx, caller, principal, "s3:GetObject", action, credentialScope, resources,+ withoutObjectTags(targetContexts), region, accountId, akid)) {+ return;+ }+ // Asking to bypass governance-mode retention on a retention change or a delete takes+ // s3:BypassGovernanceRetention as well, as the API reference says for both. The user guide+ // says the permission does not apply to annotation operations.+ if (GOVERNANCE_BYPASS_ACTIONS.contains(action)+ && "true".equalsIgnoreCase(ctx.getHeaderString("x-amz-bypass-governance-retention"))+ && abortIfDenied(ctx, caller, principal, "s3:BypassGovernanceRetention", action, credentialScope,+ resources, targetContexts, region, accountId, akid)) {+ return;+ }+ // An object created with an ACL, tags, a retention period or a legal hold also needs that+ // setting's own action, as the permissions table says for PutObject, CopyObject and+ // CreateMultipartUpload. Each is checked with the PutObject context, which carries the+ // request's tags and Object Lock settings.+ if ("s3:PutObject".equals(action) && isObjectCreation(ctx)) {+ for (String creationAction+ : S3ObjectActions.objectCreationActions(ctx::getHeaderString, requestTagging(ctx))) {+ if (abortIfDenied(ctx, caller, principal, creationAction, action, credentialScope, resources,+ targetContexts, region, accountId, akid)) {+ return;+ }+ }+ }+ // GetObjectAttributes needs s3:GetObjectAttributes beside s3:GetObject, and for a version+ // s3:GetObjectVersionAttributes beside s3:GetObjectVersion, as its API reference says. Both+ // carry the object's tags and the version id, so the read's context serves for either. A+ // denial is recorded as GetObjectAttributes, the operation it refuses.+ if (("s3:GetObject".equals(action) || "s3:GetObjectVersion".equals(action))+ && "GET".equalsIgnoreCase(ctx.getMethod())+ && ctx.getUriInfo().getQueryParameters().containsKey("attributes")) {+ String attributesAction = S3ObjectActions.forVersion("s3:GetObjectAttributes",+ ctx.getUriInfo().getQueryParameters().getFirst("versionId"));+ abortIfDenied(ctx, caller, principal, attributesAction, attributesAction, credentialScope, resources,+ targetContexts, region, accountId, akid);}}@@ -566,6 +606,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// presigned URLs add, is a DeleteObject.private static final Set<String> NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation");+ private static final Set<String> GOVERNANCE_BYPASS_ACTIONS =+ Set.of("s3:PutObjectRetention", "s3:DeleteObject", "s3:DeleteObjectVersion");+// PutObject and CopyObject are any PUT S3Controller does not run as UploadPart or UploadPartCopy,// which name both an uploadId and a partNumber; CompleteMultipartUpload is a POST naming its// upload, without ?uploads.@@ -578,6 +621,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {return "POST".equalsIgnoreCase(ctx.getMethod()) && namesUpload && !params.containsKey("uploads");}+ /**+ * PutObject and CopyObject (a PUT naming no uploadId, which would make it UploadPart) and+ * CreateMultipartUpload (a POST naming {@code uploads}): the operations checked as+ * {@code s3:PutObject} that build a new object from the request's headers.+ */+ private static boolean isObjectCreation(ContainerRequestContext ctx) {+ MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();+ if ("PUT".equalsIgnoreCase(ctx.getMethod())) {+ return !params.containsKey("uploadId");+ }+ return "POST".equalsIgnoreCase(ctx.getMethod()) && params.containsKey("uploads");+ }++ /** The request's {@code x-amz-tagging}: the header, or the query parameter a presigner may place it in. */+ private static String requestTagging(ContainerRequestContext ctx) {+ String header = ctx.getHeaderString("x-amz-tagging");+ return header != null ? header : ctx.getUriInfo().getQueryParameters().getFirst("x-amz-tagging");+ }+private static boolean isPlainDeleteObject(ContainerRequestContext ctx) {return "DELETE".equalsIgnoreCase(ctx.getMethod())&& ctx.getUriInfo().getQueryParameters().keySet().stream()@@ -773,6 +835,19 @@ public class IamEnforcementFilter implements ContainerRequestFilter {String action, String credentialScope, List<String> resources,List<Map<String, List<String>>> targetContexts,String region, String accountId, String akid) {+ return abortIfDenied(ctx, caller, principal, action, action, credentialScope, resources, targetContexts,+ region, accountId, akid);+ }++ /**+ * Checks {@code action}, which may be one the operation needs besides its own. A denial names+ * {@code action}, the permission that is missing, while the CloudTrail event records+ * {@code operationAction}, the operation that was refused.+ */+ private boolean abortIfDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,+ String action, String operationAction, String credentialScope,+ List<String> resources, List<Map<String, List<String>>> targetContexts,+ String region, String accountId, String akid) {for (String resource : resources) {List<ResourcePolicyProvider.ResourcePolicy> resourcePolicies = resolveResourcePolicies(credentialScope, resource);String resourceOwnerAccountId = resourcePolicies.isEmpty() ? null : resourcePolicies.getFirst().ownerAccountId();@@ -812,7 +887,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {+ " is not authorized to perform: " + action+ " on resource: \"" + resource + "\""+ " because no identity-based policy allows the " + action + " action";- emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);+ emitS3DenialIfApplicable(akid, operationAction, resource, ctx, region, denyMessage);ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx, resource));return true;}@@ -1162,6 +1237,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// registry, so we distinguish via httpMethod. The POST operations checked as// s3:PutObject or s3:GetObject (multipart create and complete, Select) cannot// be told apart from the action, so they get no name rather than a wrong one.+ // The GetObjectAttributes actions are the operation its own check refuses.if ("POST".equalsIgnoreCase(httpMethod)) {return null;}@@ -1169,6 +1245,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {case "s3:GetObject", "s3:GetObjectVersion" ->"HEAD".equalsIgnoreCase(httpMethod) ? "HeadObject" : "GetObject";case "s3:PutObject" -> "PutObject";+ case "s3:PutObjectRetention" -> "PutObjectRetention";+ case "s3:GetObjectAttributes", "s3:GetObjectVersionAttributes" -> "GetObjectAttributes";case "s3:DeleteObject", "s3:DeleteObjectVersion" -> "DeleteObject";case "s3:ListBucket" -> "ListObjects";case "s3:ListAllMyBuckets" -> "ListBuckets";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.javaindex e2012ee71c..841e4f3ffc 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@@ -107,6 +107,9 @@ public class S3Controller {"ObjectLockConfigurationNotFoundError", "OwnershipControlsNotFoundError","ReplicationConfigurationNotFoundError");+ /** The errors S3Service answers a read of an object that is not there with. */+ private static final Set<String> MISSING_OBJECT_ERRORS = Set.of("NoSuchBucket", "NoSuchKey", "NoSuchVersion");+private static final Logger LOG = Logger.getLogger(S3Controller.class);private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")@@ -1719,14 +1722,7 @@ public class S3Controller {S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(s3Service.isAuthEnforced(), httpHeaders, uriInfo);s3Service.authorizeSignedRequest(authorization);- // A blank header counts as absent, as it does in IamEnforcementFilter.filter(), so a presigned- // request cannot shed its query credential, and with it every per-key check, by adding one.- String authorizationHeader = httpHeaders.getHeaderString("Authorization");- if (authorizationHeader != null && authorizationHeader.isBlank()) {- authorizationHeader = null;- }- String iamCredential = IamEnforcementFilter.requestAuthorization(- authorizationHeader, uriInfo.getQueryParameters());+ String iamCredential = iamCredential(httpHeaders, uriInfo);List<XmlParser.KeyVersion> authorizedEntries = new ArrayList<>();List<S3Service.DeleteError> authorizationErrors = new ArrayList<>();for (XmlParser.KeyVersion entry : entries) {@@ -3072,6 +3068,7 @@ public class S3Controller {CopySourceRef sourceObject = parseCopySource(copySource);String sourceBucket = sourceObject.bucket();authorizeCopySourceRead(httpHeaders, sourceObject, authorization);+ authorizeCopiedTags(httpHeaders, uriInfo, sourceObject, destBucket, destKey, authorization);String copyContentEncoding = toPersistedContentEncoding(httpHeaders.getHeaderString("Content-Encoding"));String copyContentDisposition = httpHeaders.getHeaderString("Content-Disposition");String copyCacheControl = httpHeaders.getHeaderString("Cache-Control");@@ -4396,6 +4393,56 @@ public class S3Controller {source.bucket(), source.objectKey(), source.versionId(), authorization);}+ /**+ * A copy under the default {@code COPY} tagging directive gives the new object the source's tags,+ * and the permissions table makes a copy that puts the object with tags need s3:PutObjectTagging+ * on the destination, as an object created with tags does. IamEnforcementFilter checks the tags a+ * request sends; only the source tells whether a copy carries any, so this checks them here, once+ * {@link #authorizeCopySourceRead} has allowed the source to be read. The source is read only when+ * IAM enforcement is on and the request names a credential, the header's or a presigned URL's.+ */+ private void authorizeCopiedTags(HttpHeaders httpHeaders, UriInfo uriInfo, CopySourceRef source,+ String destBucket, String destKey, S3Service.RequestAuthorization authorization) {+ String credential = iamCredential(httpHeaders, uriInfo);+ if (!config.services().iam().enforcementEnabled() || credential == null+ || "REPLACE".equalsIgnoreCase(httpHeaders.getHeaderString("x-amz-tagging-directive"))) {+ return;+ }+ Map<String, String> sourceTags;+ try {+ sourceTags = s3Service.getObjectTagging(source.bucket(), source.objectKey(), source.versionId());+ } catch (AwsException e) {+ if (!MISSING_OBJECT_ERRORS.contains(e.getErrorCode())) {+ throw e;+ }+ // A missing source has no tags to copy, and the copy reports it missing.+ return;+ }+ if (sourceTags.isEmpty()) {+ return;+ }+ String action = "s3:PutObjectTagging";+ String resource = S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(destBucket), destBucket, destKey);+ S3Service.SignedPrincipalResourcePolicyEvaluation resourcePolicyEvaluation =+ s3Service.signedPrincipalResourcePolicyDecision(destBucket, action, resource, authorization);+ iamEnforcementFilter.authorizeAdditionalResource(credential, action, resource,+ resourcePolicyEvaluation.decision(), resourcePolicyEvaluation.resourceOwnerAccountId());+ }++ /**+ * The credential IAM evaluates a check S3Controller makes itself against: the Authorization header,+ * or a presigned request's query credential. A blank header counts as absent, as it does in+ * IamEnforcementFilter.filter(), so a presigned request cannot shed its query credential, and with+ * it the check, by adding one.+ */+ private static String iamCredential(HttpHeaders httpHeaders, UriInfo uriInfo) {+ String authorizationHeader = httpHeaders.getHeaderString("Authorization");+ if (authorizationHeader != null && authorizationHeader.isBlank()) {+ authorizationHeader = null;+ }+ return IamEnforcementFilter.requestAuthorization(authorizationHeader, uriInfo.getQueryParameters());+ }+/*** Splits a raw {@code x-amz-copy-source} header into decoded source bucket, object key and optional* {@code versionId}. Shared by {@code CopyObject} and {@code UploadPartCopy}.diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectActions.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectActions.javaindex 9a78b220b3..25827d9833 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectActions.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectActions.java@@ -1,14 +1,31 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.IamConditionContextResolver;+import org.jboss.logging.Logger;++import java.net.URLDecoder;+import java.nio.charset.StandardCharsets;+import java.time.Duration;+import java.time.Instant;+import java.time.format.DateTimeParseException;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;import java.util.Map;+import java.util.Set;+import java.util.function.Function;/**- * The version actions AWS checks for an S3 object request that names a {@code versionId}, in place of- * the action the request is otherwise checked as. The source is the Service Authorization Reference- * for S3, which gives each its own action.+ * The IAM actions AWS checks for an S3 object request in place of, or besides, the one its operation+ * names, and the condition keys an object creation offers those checks. The sources are the user+ * guide's "Required permissions for S3 API operations" table, and the Service Authorization Reference+ * for the version actions and the condition keys.*/public final class S3ObjectActions {+ private static final Logger LOG = Logger.getLogger(S3ObjectActions.class);+/*** The object actions that have a version counterpart, which AWS checks in their place when the* request names a {@code versionId}. Retention, legal hold, restore and the multipart actions@@ -22,11 +39,16 @@ public final class S3ObjectActions {Map.entry("s3:GetObjectTagging", "s3:GetObjectVersionTagging"),Map.entry("s3:PutObjectTagging", "s3:PutObjectVersionTagging"),Map.entry("s3:DeleteObjectTagging", "s3:DeleteObjectVersionTagging"),+ Map.entry("s3:GetObjectAttributes", "s3:GetObjectVersionAttributes"),Map.entry("s3:GetObjectAnnotation", "s3:GetObjectVersionAnnotation"),Map.entry("s3:ListObjectAnnotations", "s3:ListObjectVersionAnnotations"),Map.entry("s3:PutObjectAnnotation", "s3:PutObjectVersionAnnotation"),Map.entry("s3:DeleteObjectAnnotation", "s3:DeleteObjectVersionAnnotation"));+ private static final List<String> GRANT_HEADERS = List.of(+ "x-amz-grant-read", "x-amz-grant-write", "x-amz-grant-read-acp", "x-amz-grant-write-acp",+ "x-amz-grant-full-control");+private S3ObjectActions() {}@@ -39,4 +61,162 @@ public final class S3ObjectActions {public static boolean isVersionAction(String action) {return VERSION_ACTIONS.containsValue(action);}++ /**+ * The actions a PutObject, CopyObject or CreateMultipartUpload needs besides {@code s3:PutObject},+ * one for each thing its headers set on the new object: an ACL, tags, a retention period, a legal+ * hold. The permissions table marks each one conditionally required for all three operations. A+ * CopyObject applies the request's tags only under {@code x-amz-tagging-directive: REPLACE}; under+ * the default {@code COPY} it gives the new object the source's tags, which S3Controller checks,+ * since only it reads the source.+ *+ * @param header reads one request header, null when it is absent+ * @param tagging the request's {@code x-amz-tagging}, from its header or, for a presigned URL, its+ * query string+ */+ public static List<String> objectCreationActions(Function<String, String> header, String tagging) {+ List<String> actions = new ArrayList<>();+ if (header.apply("x-amz-acl") != null || GRANT_HEADERS.stream().anyMatch(name -> header.apply(name) != null)) {+ actions.add("s3:PutObjectAcl");+ }+ if (tagging != null && !tagging.isBlank() && appliesRequestTags(header)) {+ actions.add("s3:PutObjectTagging");+ }+ if (header.apply("x-amz-object-lock-mode") != null+ || header.apply("x-amz-object-lock-retain-until-date") != null) {+ actions.add("s3:PutObjectRetention");+ }+ if (header.apply("x-amz-object-lock-legal-hold") != null) {+ actions.add("s3:PutObjectLegalHold");+ }+ return actions;+ }++ /**+ * The condition keys an object creation offers {@code s3:PutObject} and each of+ * {@link #objectCreationActions}: {@code s3:RequestObjectTag/<key>} and+ * {@code s3:RequestObjectTagKeys} from the tags it applies, which a copy under the default+ * {@code COPY} directive takes from the source rather than the request, and the Object Lock keys+ * from its Object Lock headers. Null when it offers none.+ *+ * @param header reads one request header, null when it is absent+ * @param tagging the request's {@code x-amz-tagging}, as {@link #objectCreationActions} takes it+ * @param now the moment {@code s3:object-lock-remaining-retention-days} counts from+ */+ public static Map<String, List<String>> objectCreationConditions(Function<String, String> header, String tagging,+ Instant now) {+ Map<String, List<String>> conditions = new LinkedHashMap<>();+ Map<String, List<String>> tags = appliesRequestTags(header) ? requestObjectTagConditions(tagging) : null;+ if (tags != null) {+ conditions.putAll(tags);+ }+ Map<String, List<String>> lock = objectLockConditions(header.apply("x-amz-object-lock-mode"),+ header.apply("x-amz-object-lock-retain-until-date"), header.apply("x-amz-object-lock-legal-hold"),+ now);+ if (lock != null) {+ conditions.putAll(lock);+ }+ return conditions.isEmpty() ? null : conditions;+ }++ /**+ * Whether the new object gets the request's {@code x-amz-tagging}: a PutObject's and a+ * CreateMultipartUpload's always, a CopyObject's only under {@code x-amz-tagging-directive:+ * REPLACE}. Under the default {@code COPY} a copy keeps the source's tags and ignores the header.+ */+ private static boolean appliesRequestTags(Function<String, String> header) {+ return header.apply("x-amz-copy-source") == null+ || "REPLACE".equalsIgnoreCase(header.apply("x-amz-tagging-directive"));+ }++ /**+ * {@code s3:RequestObjectTag/<key>} and {@code s3:RequestObjectTagKeys} from an+ * {@code x-amz-tagging} value. Null when it names no tag.+ */+ static Map<String, List<String>> requestObjectTagConditions(String tagging) {+ if (tagging == null || tagging.isBlank()) {+ return null;+ }+ Map<String, List<String>> conditions = new LinkedHashMap<>();+ Set<String> requestedKeys = new LinkedHashSet<>();+ for (String pair : tagging.split("&")) {+ int eq = pair.indexOf('=');+ if (eq <= 0) {+ continue;+ }+ String name = urlDecode(pair.substring(0, eq));+ String value = urlDecode(pair.substring(eq + 1));+ if (name == null || value == null) {+ continue;+ }+ conditions.put(IamConditionContextResolver.REQUEST_OBJECT_TAG_PREFIX + name, List.of(value));+ requestedKeys.add(name);+ }+ if (!requestedKeys.isEmpty()) {+ conditions.put(IamConditionContextResolver.REQUEST_OBJECT_TAG_KEYS, new ArrayList<>(requestedKeys));+ }+ return conditions.isEmpty() ? null : conditions;+ }++ /**+ * {@code s3:object-lock-mode}, {@code s3:object-lock-retain-until-date},+ * {@code s3:object-lock-remaining-retention-days} and {@code s3:object-lock-legal-hold} from the+ * Object Lock settings a request applies. A setting the request leaves out offers no key, and+ * null is returned when it leaves out all of them.+ */+ public static Map<String, List<String>> objectLockConditions(String mode, String retainUntilDate,+ String legalHold, Instant now) {+ Map<String, List<String>> conditions = new LinkedHashMap<>();+ if (mode != null && !mode.isBlank()) {+ conditions.put(IamConditionContextResolver.OBJECT_LOCK_MODE, List.of(mode));+ }+ if (legalHold != null && !legalHold.isBlank()) {+ conditions.put(IamConditionContextResolver.OBJECT_LOCK_LEGAL_HOLD, List.of(legalHold));+ }+ if (retainUntilDate != null && !retainUntilDate.isBlank()) {+ conditions.put(IamConditionContextResolver.OBJECT_LOCK_RETAIN_UNTIL_DATE, List.of(retainUntilDate));+ Long days = remainingRetentionDays(retainUntilDate, now);+ if (days != null) {+ conditions.put(IamConditionContextResolver.OBJECT_LOCK_REMAINING_RETENTION_DAYS,+ List.of(Long.toString(days)));+ }+ }+ return conditions.isEmpty() ? null : conditions;+ }++ /**+ * Days from {@code now} until {@code retainUntilDate}, a part day counted as a whole one, and 0+ * for a date that has passed. AWS documents the key but not its arithmetic. Rounding up keeps a+ * Deny on retention longer than N days, the user guide's example, from letting through a date+ * some hours past N days. Null for a date S3Controller would not parse either.+ */+ private static Long remainingRetentionDays(String retainUntilDate, Instant now) {+ Instant until;+ try {+ until = Instant.parse(retainUntilDate);+ } catch (DateTimeParseException e) {+ return null;+ }+ Duration remaining = Duration.between(now, until);+ if (remaining.isNegative() || remaining.isZero()) {+ return 0L;+ }+ long days = remaining.toDays();+ return remaining.minusDays(days).isZero() ? days : days + 1;+ }++ /**+ * Null for a value {@code URLDecoder} refuses, such as the {@code %zz} of a malformed+ * {@code x-amz-tagging} header. The caller drops the pair rather than letting the+ * {@code IllegalArgumentException} out of the check, where it becomes a 500 in place of the+ * 400 {@code InvalidTag} the handler returns for the same header.+ */+ private static String urlDecode(String value) {+ try {+ return URLDecoder.decode(value, StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ LOG.debugv(e, "Undecodable tag component in the condition context: {0}", value);+ return null;+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.javaindex 75d3dd1cd3..8fe2df3d07 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java@@ -27,6 +27,9 @@ import org.mockito.ArgumentCaptor;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.nio.charset.StandardCharsets;+import java.time.Clock;+import java.time.Instant;+import java.time.ZoneOffset;import java.util.HashSet;import java.util.List;import java.util.Map;@@ -49,6 +52,8 @@ import static org.mockito.Mockito.when;class IamConditionContextResolverTest {+ private static final Instant LOCK_NOW = Instant.parse("2026-01-01T00:00:00Z");+private final ObjectMapper mapper = new ObjectMapper();private DynamoDbService dynamoDbService;private Instance<DynamoDbFacade> dynamoDbFacadeInstance;@@ -315,6 +320,48 @@ class IamConditionContextResolverTest {}}+ @Test+ void objectLockKeysComeFromTheHeadersOfTheObjectCreated() {+ ContainerRequestContext request = s3Request("/bucket/object", "");+ when(request.getHeaderString("x-amz-object-lock-mode")).thenReturn("GOVERNANCE");+ when(request.getHeaderString("x-amz-object-lock-retain-until-date")).thenReturn("2026-01-11T00:00:00Z");+ when(request.getHeaderString("x-amz-object-lock-legal-hold")).thenReturn("ON");+ Map<String, List<String>> conditions = resolverAt(LOCK_NOW).resolve("s3", "s3:PutObject", request);+ assertEquals(List.of("GOVERNANCE"), conditions.get("s3:object-lock-mode"));+ assertEquals(List.of("2026-01-11T00:00:00Z"), conditions.get("s3:object-lock-retain-until-date"));+ assertEquals(List.of("10"), conditions.get("s3:object-lock-remaining-retention-days"));+ assertEquals(List.of("ON"), conditions.get("s3:object-lock-legal-hold"));+ }++ @Test+ void remainingRetentionDaysCountAPartDayAsAWholeOne() {+ assertEquals(List.of("10"), remainingRetentionDays("2026-01-11T00:00:00Z"));+ assertEquals(List.of("11"), remainingRetentionDays("2026-01-11T00:00:01Z"));+ assertEquals(List.of("1"), remainingRetentionDays("2026-01-01T00:00:01Z"));+ assertEquals(List.of("0"), remainingRetentionDays("2025-12-31T00:00:00Z"));+ assertNull(remainingRetentionDays("not-a-date"), "a date S3 would not parse offers no count");+ }++ @Test+ void legalHoldStatusComesFromTheBody() {+ ContainerRequestContext request = s3Request("/bucket/object", "<LegalHold><Status>OFF</Status></LegalHold>");+ assertEquals(Map.of("s3:object-lock-legal-hold", List.of("OFF")),+ resolver.resolve("s3", "s3:PutObjectLegalHold", request));+ }++ private List<String> remainingRetentionDays(String until) {+ ContainerRequestContext request = s3Request("/bucket/object",+ "<Retention><Mode>GOVERNANCE</Mode><RetainUntilDate>" + until + "</RetainUntilDate></Retention>");+ return resolverAt(LOCK_NOW).resolve("s3", "s3:PutObjectRetention", request)+ .get("s3:object-lock-remaining-retention-days");+ }++ @SuppressWarnings("unchecked")+ private IamConditionContextResolver resolverAt(Instant now) {+ return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),+ mock(Instance.class), requestContext, config, Clock.fixed(now, ZoneOffset.UTC));+ }+@Testvoid resolvesDynamoDbLeadingKeysForGetItem() {ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.javaindex 24f9e845c6..ad8249a31f 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java@@ -115,6 +115,10 @@ class IamEnforcementFilterTest {}private IamEnforcementFilter newFilter(CurrentVertxRequest currentVertxRequest) {+ return newFilter(currentVertxRequest, mock(CloudTrailService.class));+ }++ private IamEnforcementFilter newFilter(CurrentVertxRequest currentVertxRequest, CloudTrailService cloudTrail) {@SuppressWarnings("unchecked")Instance<ScpProvider> scpProvider =mock(Instance.class);@@ -122,7 +126,7 @@ class IamEnforcementFilterTest {return new IamEnforcementFilter(config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,requestContext, conditionContextResolver,- mock(CloudTrailService.class),+ cloudTrail,currentVertxRequest,catalog, scpProvider, sessionAccountLookup);}@@ -948,6 +952,45 @@ class IamEnforcementFilterTest {eq("s3:GetObject"), eq("arn:aws:s3:::bucket//key"), any());}+ @Test+ void aScopedPresignedPutCannotApplyASettingItsUrlDoesNotGrant() {+ // A generated URL's session policy grants only its own action, and the scope guard refuses+ // the extra actions of an object creation on its own: the policies here allow everything,+ // so only the guard can deny the legal hold.+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);+ CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);+ RoutingContext routingContext = mock(RoutingContext.class);+ HttpServerRequest httpRequest = mock(HttpServerRequest.class);+ UriInfo uriInfo = mock(UriInfo.class);+ when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());+ when(containerRequest.getUriInfo()).thenReturn(uriInfo);+ when(containerRequest.getMethod()).thenReturn("PUT");+ String auth = "AWS4-HMAC-SHA256 Credential=ASIASCOPE/20260927/us-east-1/s3/aws4_request, "+ + "SignedHeaders=host, Signature=abc";+ requestContext.setAccountId("000000000000");+ when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);+ when(containerRequest.getHeaderString("x-amz-object-lock-legal-hold")).thenReturn("ON");+ when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");+ when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");+ when(iamService.resolveCallerContext(eq("ASIASCOPE"), any()))+ .thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));+ when(iamService.presignedScope("ASIASCOPE"))+ .thenReturn(Optional.of(new IamService.PresignedScope(+ "s3:PutObject", "arn:aws:s3:::bucket/key")));+ when(currentVertxRequest.getCurrent()).thenReturn(routingContext);+ when(routingContext.request()).thenReturn(httpRequest);+ when(httpRequest.path()).thenReturn("/bucket/key");+ when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(IamPolicyEvaluator.Decision.ALLOW);++ newFilter(currentVertxRequest).filter(containerRequest);++ ArgumentCaptor<Response> denied = ArgumentCaptor.captor();+ verify(containerRequest).abortWith(denied.capture());+ assertEquals(403, denied.getValue().getStatus());+ assertTrue(entityString(denied.getValue()).contains("s3:PutObjectLegalHold"));+ }+private void assertScopedPresignedRequestWithoutHttpRequestIsDenied(RoutingContext routingContext) {ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);@@ -1968,6 +2011,66 @@ class IamEnforcementFilterTest {return entity.toString();}+ @Test+ void aDeniedExtraActionNamesThePermissionAndRecordsTheOperation() {+ // A PutObject placing a legal hold also needs s3:PutObjectLegalHold. The denial names that+ // permission, while CloudTrail records PutObject, the operation that was refused.+ assertEquals("PutObject", deniedExtraActionEvent("PUT", new MultivaluedHashMap<>(),+ "x-amz-object-lock-legal-hold", "ON", "s3:PutObject", "s3:PutObjectLegalHold"));+ // A retention change asking for the bypass is recorded as the retention change.+ MultivaluedHashMap<String, String> retention = new MultivaluedHashMap<>();+ retention.putSingle("retention", "");+ assertEquals("PutObjectRetention", deniedExtraActionEvent("PUT", retention,+ "x-amz-bypass-governance-retention", "true", "s3:PutObjectRetention",+ "s3:BypassGovernanceRetention"));+ // GetObjectAttributes is checked as the read and as its own action; denied the second, it is+ // recorded as GetObjectAttributes, not as the read.+ MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();+ attributes.putSingle("attributes", "");+ assertEquals("GetObjectAttributes", deniedExtraActionEvent("GET", attributes,+ "x-amz-object-attributes", "ETag", "s3:GetObject", "s3:GetObjectAttributes"));+ }++ /**+ * Runs an S3 request whose own action is allowed and whose extra action is denied, asserts the+ * denial names the extra action, and returns the event name CloudTrail recorded for it.+ */+ private String deniedExtraActionEvent(String method, MultivaluedHashMap<String, String> query, String header,+ String headerValue, String allowedAction, String deniedAction) {+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);+ UriInfo uriInfo = mock(UriInfo.class);+ when(uriInfo.getPath()).thenReturn("/bucket/object");+ when(uriInfo.getQueryParameters()).thenReturn(query);+ when(containerRequest.getUriInfo()).thenReturn(uriInfo);+ when(containerRequest.getMethod()).thenReturn(method);+ String auth = "AWS4-HMAC-SHA256 Credential=AKIAEXTRA/20260706/us-east-1/s3/aws4_request, "+ + "SignedHeaders=host, Signature=abc";+ requestContext.setAccountId("222233334444");+ requestContext.setRegion("us-east-1");+ when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAEXTRA");+ when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);+ when(containerRequest.getHeaderString(header)).thenReturn(headerValue);+ when(actionRegistry.resolve("s3", containerRequest)).thenReturn(allowedAction);+ when(iamService.resolveCallerContext(eq("AKIAEXTRA"), any())).thenReturn(CallerContext.of(List.of()));+ when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))+ .thenReturn(List.of("arn:aws:s3:::bucket/object"));+ when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(allowedAction), any(), any()))+ .thenReturn(IamPolicyEvaluator.Decision.ALLOW);+ when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(deniedAction), any(), any()))+ .thenReturn(IamPolicyEvaluator.Decision.DENY);+ CloudTrailService cloudTrail = mock(CloudTrailService.class);++ newFilter(mock(CurrentVertxRequest.class), cloudTrail).filter(containerRequest);++ ArgumentCaptor<Response> denied = ArgumentCaptor.captor();+ verify(containerRequest).abortWith(denied.capture());+ assertEquals(403, denied.getValue().getStatus());+ assertTrue(entityString(denied.getValue()).contains(deniedAction));+ ArgumentCaptor<CloudTrailService.S3EventInput> event = ArgumentCaptor.captor();+ verify(cloudTrail).emitS3DataEvent(event.capture());+ return event.getValue().eventName();+ }+@Testvoid s3ResourceAccountIsTheBucketOwnerNotTheCallerOnCrossAccountAccess() {// An S3 bucket ARN carries no account, so aws:ResourceAccount has to come from S3 state.diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterUnitTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterUnitTest.javaindex ed94e70ad6..fba9c86a65 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterUnitTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterUnitTest.java@@ -93,6 +93,16 @@ class IamEnforcementFilterUnitTest {IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectVersionTagging", "DELETE"));}+ @Test+ void extraActionChecks_emitAsTheOperationTheyRefuse() {+ assertEquals("PutObjectRetention",+ IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectRetention", "PUT"));+ assertEquals("GetObjectAttributes",+ IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectAttributes", "GET"));+ assertEquals("GetObjectAttributes",+ IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionAttributes", "GET"));+ }+@Testvoid postOperations_returnNullRatherThanTheWrongName() {// CreateMultipartUpload and CompleteMultipartUpload are checked as s3:PutObject, anddiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamTagKeysEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamTagKeysEnforcementIntegrationTest.javaindex bc34f29a06..ed67cbcfae 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamTagKeysEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamTagKeysEnforcementIntegrationTest.java@@ -69,7 +69,7 @@ class IamTagKeysEnforcementIntegrationTest {@ValueSource(strings = {"Admin", "team"})void s3ObjectUploadRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {String bucket = bucket();- String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");+ String key = scopedUploader();String path = "/" + bucket + "/object";given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "%54eam=payments").body("original").put(path).then().statusCode(200);@@ -117,7 +117,7 @@ class IamTagKeysEnforcementIntegrationTest {@ValueSource(strings = {"Admin", "team"})void s3QueryTagKeysAreCheckedBeforeAnUpload(String forbiddenKey) {String bucket = bucket();- String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");+ String key = scopedUploader();String path = "/" + bucket + "/object";given().header("Authorization", auth(key, "s3")).queryParam("x-amz-tagging", "%54eam=payments").body("original").put(path).then().statusCode(200);@@ -134,7 +134,7 @@ class IamTagKeysEnforcementIntegrationTest {@Testvoid s3TagHeaderTakesPrecedenceOverTheQuery() {String bucket = bucket();- String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");+ String key = scopedUploader();String path = "/" + bucket + "/object";given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments").queryParam("x-amz-tagging", "Admin=true").body("original").put(path).then().statusCode(200);@@ -155,7 +155,7 @@ class IamTagKeysEnforcementIntegrationTest {.put(path).then().statusCode(200).extract().header("ETag");String key = userWithPolicy("""{"Version":"2012-10-17","Statement":[- {"Effect":"Allow","Action":"s3:PutObject","Resource":"*"},+ {"Effect":"Allow","Action":["s3:PutObject","s3:PutObjectTagging"],"Resource":"*"},{"Effect":"Allow","Action":"s3:GetObject","Resource":"*","Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}""");@@ -165,7 +165,7 @@ class IamTagKeysEnforcementIntegrationTest {.then().statusCode(200).body(equalTo("original"));String allowedKey = userWithPolicy("""{"Version":"2012-10-17","Statement":[{"Effect":"Allow",- "Action":["s3:PutObject","s3:GetObject"],"Resource":"*"}]}+ "Action":["s3:PutObject","s3:PutObjectTagging","s3:GetObject"],"Resource":"*"}]}""");given().header("Authorization", auth(allowedKey, "s3")).header("x-amz-tagging", "Team=payments").header("If-Match", etag).body("allowed").put(path).then().statusCode(200);@@ -188,6 +188,15 @@ class IamTagKeysEnforcementIntegrationTest {""".formatted(action, conditionKey));}+ /** A tagged upload needs s3:PutObjectTagging beside s3:PutObject, and both are held to the keys. */+ private String scopedUploader() {+ return userWithPolicy("""+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Action":["s3:PutObject","s3:PutObjectTagging"],"Resource":"*",+ "Condition":{"ForAllValues:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}+ """);+ }+private String userWithPolicy(String policy) {String user = "tagkeys-" + UUID.randomUUID();String accessKey = createUser(cleanup, endpoint.getPort(), auth("test", "iam"), user).accessKeyId();diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectOperationsIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectOperationsIamEnforcementIntegrationTest.javaindex 4850ca5c3a..5886d0a98d 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectOperationsIamEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectOperationsIamEnforcementIntegrationTest.java@@ -25,7 +25,9 @@ import static org.hamcrest.Matchers.not;* and the other POST operations, which no rule mapped, the multipart operations that were checked as* a plain read or delete, the object-lock operations, the version actions a versionId selects, and* the bucket configurations. A request naming several sub-resources is checked as the one S3 runs,- * and the version actions carry the version id and the version's tags.+ * and the version actions carry the version id and the version's tags. An operation also needs the+ * actions it requires besides its own: an object creation those of the settings it applies,+ * GetObjectAttributes its own action beside the read, and a governance bypass its permission.*/@QuarkusTest@TestProfile(IamEnforcementProfile.class)@@ -178,6 +180,216 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {f.user().queryParam("retention", "").when().get(f.path("a/locked")).then().statusCode(200);}+ @Test+ void bypassingGovernanceRetentionNeedsBypassGovernanceRetention() {+ Fixture f = new Fixture("bypass", true);+ f.seed("a/governed");+ f.admin().queryParam("retention", "")+ .body(retention("2031-01-01T00:00:00Z"))+ .when().put(f.path("a/governed")).then().statusCode(200);++ f.policy(f.allow("s3:PutObjectRetention"));+ denied(f.putRetention("a/governed", "2030-01-01T00:00:00Z", true), "s3:BypassGovernanceRetention");++ f.policy(f.allow("s3:PutObjectRetention", "s3:BypassGovernanceRetention"));+ f.putRetention("a/governed", "2030-01-01T00:00:00Z", true).statusCode(200);+ }++ @Test+ void deletingWithTheBypassNeedsBypassGovernanceRetention() {+ // The DeleteObject API reference: "To use this header, you must have the+ // s3:BypassGovernanceRetention permission", whether or not the request names a version.+ Fixture f = new Fixture("delete-bypass", true);+ String versionId = f.seedVersion("a/governed");+ f.admin().queryParam("retention", "").queryParam("versionId", versionId)+ .body(retention("2031-01-01T00:00:00Z"))+ .when().put(f.path("a/governed")).then().statusCode(200);++ f.policy(f.allow("s3:DeleteObject", "s3:DeleteObjectVersion"));+ denied(f.user().header("x-amz-bypass-governance-retention", "true")+ .when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");+ denied(f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", versionId)+ .when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");++ f.policy(f.allow("s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"));+ f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", versionId)+ .when().delete(f.path("a/governed")).then().statusCode(204);+ }++ @Test+ void deletingAnAnnotationWithTheBypassHeaderNeedsNoBypassPermission() {+ // The user guide: "The BypassGovernanceRetention permission does not apply to annotation+ // operations."+ Fixture f = new Fixture("annotation-bypass", false);+ f.seed("a/doc");+ f.admin().queryParam("annotation", "").queryParam("annotationName", "labels").body("x")+ .when().put(f.path("a/doc")).then().statusCode(200);++ f.policy(f.allow("s3:DeleteObjectAnnotation"));+ f.annotation(null).header("x-amz-bypass-governance-retention", "true")+ .when().delete(f.path("a/doc")).then().statusCode(204);+ }++ @Test+ void getObjectAttributesNeedsItsOwnActionAndTheRead() {+ // The API reference: s3:GetObject and s3:GetObjectAttributes, or for a version+ // s3:GetObjectVersion and s3:GetObjectVersionAttributes.+ Fixture f = new Fixture("attributes", true);+ String versionId = f.seedVersion("a/doc");++ f.policy(f.allow("s3:GetObject", "s3:GetObjectVersion"));+ denied(f.attributes("a/doc", null), "s3:GetObjectAttributes");+ denied(f.attributes("a/doc", versionId), "s3:GetObjectVersionAttributes");++ f.policy(f.allow("s3:GetObjectAttributes", "s3:GetObjectVersionAttributes"));+ denied(f.attributes("a/doc", null), "s3:GetObject");+ denied(f.attributes("a/doc", versionId), "s3:GetObjectVersion");++ f.policy(f.allow("s3:GetObject", "s3:GetObjectAttributes"));+ f.attributes("a/doc", null).statusCode(200);+ f.policy(f.allow("s3:GetObjectVersion", "s3:GetObjectVersionAttributes"));+ f.attributes("a/doc", versionId).statusCode(200);+ }++ @Test+ void anObjectCreatedWithTagsOrAnAclNeedsThoseActionsToo() {+ // The permissions table: s3:PutObjectTagging and s3:PutObjectAcl are conditionally required+ // for PutObject, CopyObject and CreateMultipartUpload.+ Fixture f = new Fixture("create-extras", false);+ f.seed("a/source");++ f.policy(f.allow("s3:PutObject", "s3:GetObject"));+ f.user().body("plain").when().put(f.path("a/plain")).then().statusCode(200);+ denied(f.user().header("x-amz-tagging", "env=a").body("tagged").when().put(f.path("a/tagged")).then(),+ "s3:PutObjectTagging");+ denied(f.user().header("x-amz-acl", "bucket-owner-full-control").body("acl")+ .when().put(f.path("a/acl")).then(), "s3:PutObjectAcl");+ denied(f.user().header("x-amz-grant-read", "id=000000000000").body("grant")+ .when().put(f.path("a/grant")).then(), "s3:PutObjectAcl");+ denied(f.user().header("x-amz-tagging", "env=a").queryParam("uploads", "")+ .when().post(f.path("a/upload")).then(), "s3:PutObjectTagging");+ denied(f.user().header("x-amz-acl", "private").queryParam("uploads", "")+ .when().post(f.path("a/upload")).then(), "s3:PutObjectAcl");+ denied(f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=a")+ .when().put(f.path("a/copy")).then(), "s3:PutObjectTagging");+ denied(f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-acl", "private")+ .when().put(f.path("a/copy")).then(), "s3:PutObjectAcl");+ // Without REPLACE a copy puts the source's tags on the new object, so a tagged source needs+ // the tagging action too, and an untagged one does not, whatever tags the request sends.+ denied(f.copy().when().put(f.path("a/copy")).then(), "s3:PutObjectTagging");+ f.admin().body("untagged").when().put(f.path("a/untagged")).then().statusCode(200);+ f.copyOf("a/untagged").header("x-amz-tagging", "env=a").when().put(f.path("a/copy")).then()+ .statusCode(200);++ f.policy(f.allow("s3:PutObject", "s3:GetObject", "s3:PutObjectTagging", "s3:PutObjectAcl"));+ f.user().header("x-amz-tagging", "env=a").body("tagged").when().put(f.path("a/tagged")).then()+ .statusCode(200);+ f.user().header("x-amz-acl", "bucket-owner-full-control").body("acl").when().put(f.path("a/acl")).then()+ .statusCode(200);+ f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=a")+ .when().put(f.path("a/copy")).then().statusCode(200);+ f.copy().when().put(f.path("a/copied-tags")).then().statusCode(200);+ f.admin().queryParam("tagging", "").when().get(f.path("a/copied-tags")).then()+ .statusCode(200).body(containsString("<Value>a</Value>"));+ }++ @Test+ void aCopyIsNotAuthorizedByTheTagsItIgnores() {+ // Under the default COPY directive a copy ignores x-amz-tagging, so the tags it names cannot+ // satisfy a condition on the new object's tags, on s3:PutObject or on an extra action.+ Fixture f = new Fixture("copy-ignored-tags", false);+ f.admin().body("untagged").when().put(f.path("a/untagged")).then().statusCode(200);+ String taggedB = "{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"b\"}}";++ f.policy(f.allow("s3:GetObject") + "," + f.allowWhen(taggedB, "s3:PutObject"));+ denied(f.copyOf("a/untagged").header("x-amz-tagging", "env=b").when().put(f.path("a/copy")).then(),+ "s3:PutObject");++ f.policy(f.allow("s3:GetObject", "s3:PutObject") + ","+ + f.allowWhen(taggedB, "s3:PutObjectAcl", "s3:PutObjectTagging"));+ denied(f.copyOf("a/untagged").header("x-amz-tagging", "env=b").header("x-amz-acl", "bucket-owner-full-control")+ .when().put(f.path("a/copy")).then(), "s3:PutObjectAcl");+ f.copyOf("a/untagged").header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=b")+ .header("x-amz-acl", "bucket-owner-full-control").when().put(f.path("a/copy")).then().statusCode(200);+ }++ @Test+ void aPresignedCopyOfATaggedSourceNeedsTheTaggingActionToo() {+ // The source's tags are checked against the presigned URL's credential, as a signed copy's+ // are against its Authorization header, and an empty header does not shed that credential.+ Fixture f = new Fixture("presigned-copy", false);+ f.seed("a/source");+ String source = "/" + f.bucket + "/a/source";++ f.policy(f.allow("s3:PutObject", "s3:GetObject"));+ denied(f.presigned().header("x-amz-copy-source", source)+ .when().put(f.presignedPath("a/copy")).then(), "s3:PutObjectTagging");+ denied(f.presigned().header("Authorization", "").header("x-amz-copy-source", source)+ .when().put(f.presignedPath("a/copy")).then(), "s3:PutObjectTagging");++ f.policy(f.allow("s3:PutObject", "s3:GetObject", "s3:PutObjectTagging"));+ f.presigned().header("x-amz-copy-source", source)+ .when().put(f.presignedPath("a/copy")).then().statusCode(200);+ }++ @Test+ void aCopyFromAMissingSourceIsReportedMissing() {+ // A source that is not there has no tags to check, and the copy answers for it.+ Fixture f = new Fixture("copy-missing", false);+ f.policy(f.allow("s3:PutObject", "s3:GetObject"));+ f.copyOf("a/missing").when().put(f.path("a/copy")).then()+ .statusCode(404).body(containsString("NoSuchKey"));+ }++ @Test+ void anObjectCreatedWithObjectLockSettingsNeedsTheirActions() {+ // The permissions table: s3:PutObjectRetention and s3:PutObjectLegalHold are conditionally+ // required for PutObject, CopyObject and CreateMultipartUpload.+ Fixture f = new Fixture("create-lock", true);++ f.policy(f.allow("s3:PutObject"));+ denied(f.user().header("x-amz-object-lock-mode", "GOVERNANCE")+ .header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")+ .when().put(f.path("a/retained")).then(), "s3:PutObjectRetention");+ denied(f.user().header("x-amz-object-lock-legal-hold", "OFF").body("held")+ .when().put(f.path("a/held")).then(), "s3:PutObjectLegalHold");+ denied(f.user().header("x-amz-object-lock-legal-hold", "OFF").queryParam("uploads", "")+ .when().post(f.path("a/upload")).then(), "s3:PutObjectLegalHold");++ f.policy(f.allow("s3:PutObject", "s3:PutObjectRetention", "s3:PutObjectLegalHold"));+ f.user().header("x-amz-object-lock-mode", "GOVERNANCE")+ .header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")+ .when().put(f.path("a/retained")).then().statusCode(200);+ f.user().header("x-amz-object-lock-legal-hold", "OFF").body("held")+ .when().put(f.path("a/held")).then().statusCode(200);+ }++ @Test+ void objectLockConditionKeysLimitWhatARequestMaySet() {+ // The keys come from the retention and legal-hold bodies, and from an object creation's+ // headers, which reach the extra actions it is checked as.+ Fixture f = new Fixture("lock-keys", true);+ f.seed("a/locked");+ f.policy(f.allow("s3:PutObject", "s3:PutObjectRetention", "s3:PutObjectLegalHold") + ","+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:PutObjectRetention\",\"Resource\":\"arn:aws:s3:::"+ + f.bucket + "/*\",\"Condition\":{\"DateGreaterThan\":"+ + "{\"s3:object-lock-retain-until-date\":\"2035-01-01T00:00:00Z\"}}},"+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:PutObjectLegalHold\",\"Resource\":\"arn:aws:s3:::"+ + f.bucket + "/*\",\"Condition\":{\"StringEquals\":{\"s3:object-lock-legal-hold\":\"ON\"}}}");++ denied(f.putRetention("a/locked", "2036-01-01T00:00:00Z"), "s3:PutObjectRetention");+ f.putRetention("a/locked", "2031-01-01T00:00:00Z").statusCode(200);+ denied(f.legalHold("a/locked", "ON"), "s3:PutObjectLegalHold");+ f.legalHold("a/locked", "OFF").statusCode(200);++ denied(f.user().header("x-amz-object-lock-mode", "GOVERNANCE")+ .header("x-amz-object-lock-retain-until-date", "2036-01-01T00:00:00Z").body("locked")+ .when().put(f.path("a/created")).then(), "s3:PutObjectRetention");+ f.user().header("x-amz-object-lock-mode", "GOVERNANCE")+ .header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")+ .when().put(f.path("a/created")).then().statusCode(200);+ }+@Testvoid aRequestNamingTwoSubresourcesIsCheckedAsTheOneThatRuns() {// S3 serves ?tagging before ?acl, so this request returns the object's tags.@@ -510,7 +722,48 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {}ValidatableResponse putRetention(String key, String until) {- return user().queryParam("retention", "").body(retention(until)).when().put(path(key)).then();+ return putRetention(key, until, false);+ }++ ValidatableResponse putRetention(String key, String until, boolean bypass) {+ RequestSpecification request = user().queryParam("retention", "").body(retention(until));+ if (bypass) {+ request = request.header("x-amz-bypass-governance-retention", "true");+ }+ return request.when().put(path(key)).then();+ }++ ValidatableResponse legalHold(String key, String status) {+ return user().queryParam("legal-hold", "")+ .body("<LegalHold><Status>" + status + "</Status></LegalHold>")+ .when().put(path(key)).then();+ }++ ValidatableResponse attributes(String key, String versionId) {+ RequestSpecification request = user().queryParam("attributes", "")+ .header("x-amz-object-attributes", "ETag");+ if (versionId != null) {+ request = request.queryParam("versionId", versionId);+ }+ return request.when().get(path(key)).then();+ }++ /** A user CopyObject request from the seeded {@code a/source}. */+ RequestSpecification copy() {+ return copyOf("a/source");+ }++ RequestSpecification copyOf(String key) {+ return user().header("x-amz-copy-source", "/" + bucket + "/" + key);+ }++ /** A request the user presigns with {@link #presignedPath}, which carries its credential. */+ RequestSpecification presigned() {+ return given().urlEncodingEnabled(false);+ }++ String presignedPath(String key) {+ return path(key) + "?" + EnforcementFixtures.presignedQuery(accessKeyId, "s3");}/**diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/GeneratedPreSignedUrlAuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/GeneratedPreSignedUrlAuthEnforcementIntegrationTest.javaindex b45a5d05bd..c603a43000 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/GeneratedPreSignedUrlAuthEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/GeneratedPreSignedUrlAuthEnforcementIntegrationTest.java@@ -221,6 +221,22 @@ class GeneratedPreSignedUrlAuthEnforcementIntegrationTest {.then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));}+ @Test+ void generatedPutUrlCannotSetAnAclWithoutAclPermission() {+ String bucket = "generated-presign-acl-" + UUID.randomUUID().toString().substring(0, 8);+ given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);++ URI uri = URI.create(presignGenerator.generatePresignedUrl(+ "http://localhost:" + RestAssured.port, bucket, "object.txt", "PUT", 60));+ String pathAndQuery = uri.getRawPath() + "?" + uri.getRawQuery();++ given().urlEncodingEnabled(false).header("x-amz-acl", "bucket-owner-full-control").body("with acl")+ .when().put(pathAndQuery)+ .then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));+ given().urlEncodingEnabled(false).body("without acl")+ .when().put(pathAndQuery).then().statusCode(200);+ }+@Testvoid generatedUrlsKeepLeadingSlashKeysDistinctUnderEnforcedIam() throws Exception {String bucket = "generated-presign-slash-" + UUID.randomUUID().toString().substring(0, 8);diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3DeleteObjectsIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3DeleteObjectsIamEnforcementIntegrationTest.javaindex a117dbef6e..03504a21fa 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3DeleteObjectsIamEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3DeleteObjectsIamEnforcementIntegrationTest.java@@ -14,11 +14,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.RegisterExtension;import java.net.URI;-import java.net.URLEncoder;-import java.nio.charset.StandardCharsets;import java.time.Instant;-import java.time.ZoneOffset;-import java.time.format.DateTimeFormatter;import java.util.List;import java.util.Locale;import java.util.UUID;@@ -42,10 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;class S3DeleteObjectsIamEnforcementIntegrationTest {private static final String ADMIN = "test";- private static final String REGION = "us-east-1";private static final String ACCOUNT = "000000000000";- private static final DateTimeFormatter AMZ_DATE =- DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);@InjectIamService iamService;@@ -428,16 +421,7 @@ class S3DeleteObjectsIamEnforcementIntegrationTest {}private static String presignedDeletePath(String bucket, String accessKeyId) {- String amzDate = AMZ_DATE.format(Instant.now());- String credential = URLEncoder.encode(- accessKeyId + "/" + amzDate.substring(0, 8) + "/" + REGION + "/s3/aws4_request", StandardCharsets.UTF_8);- return "/" + bucket + "?delete"- + "&X-Amz-Algorithm=AWS4-HMAC-SHA256"- + "&X-Amz-Credential=" + credential- + "&X-Amz-Date=" + amzDate- + "&X-Amz-Expires=3600"- + "&X-Amz-SignedHeaders=host"- + "&X-Amz-Signature=fakesig";+ return "/" + bucket + "?delete&" + EnforcementFixtures.presignedQuery(accessKeyId, "s3");}private static String bucket(String prefix) {diff --git a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.javaindex 2375d593bf..b7ac14dfc6 100644--- a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java+++ b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java@@ -7,6 +7,9 @@ import io.restassured.specification.RequestSpecification;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;@@ -34,6 +37,9 @@ import static io.restassured.RestAssured.given;*/public final class EnforcementFixtures {+ private static final DateTimeFormatter AMZ_DATE =+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);+private EnforcementFixtures() {// Utility class, prevent instantiation}@@ -171,6 +177,25 @@ public final class EnforcementFixtures {+ "/aws4_request, SignedHeaders=host, Signature=abc";}+ /**+ * The {@code X-Amz-*} query parameters of a SigV4 presigned request naming {@code accessKeyId},+ * scoped to {@code service} in {@code us-east-1}, to append to a path after {@code ?} or+ * {@code &}. They are dated now, so the URL has not expired, and the signature is a placeholder,+ * as {@link #auth}'s is.+ */+ public static String presignedQuery(String accessKeyId, String service) {+ String amzDate = AMZ_DATE.format(Instant.now());+ String credential = URLEncoder.encode(+ accessKeyId + "/" + amzDate.substring(0, 8) + "/us-east-1/" + service + "/aws4_request",+ StandardCharsets.UTF_8);+ return "X-Amz-Algorithm=AWS4-HMAC-SHA256"+ + "&X-Amz-Credential=" + credential+ + "&X-Amz-Date=" + amzDate+ + "&X-Amz-Expires=3600"+ + "&X-Amz-SignedHeaders=host"+ + "&X-Amz-Signature=fakesig";+ }+/*** Deletes a managed policy, and first the versions and attachments IAM wants gone before it* will. Returns quietly when the policy is already absent, so a caller can register the