mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): resolve s3:ExistingObjectTag and s3:RequestObjectTag under enforcement (#3946)
* fix(iam): resolve s3:ExistingObjectTag and s3:RequestObjectTag under enforcement The S3 condition context was built for s3:ListBucket and the bucket-tagging actions only, so a statement conditioned on an object tag never matched and a tag-conditioned allow denied everything, including what AWS allows. Object reads are now given s3:ExistingObjectTag/<key> from the object's tags, PutObject is given s3:RequestObjectTag/<key> from x-amz-tagging, and PutObjectTagging both. Which action gets which key follows what real AWS was measured to do rather than what reads naturally: s3:DeleteObject is given neither, and s3:PutObject never sees the tags of an object it is about to overwrite. A PutObject carrying If-Match is additionally authorized as s3:GetObject with the object tags stripped from the context, as measured: under a tag-conditioned GetObject allow the conditional write is denied, under a prefix-scoped one it succeeds, and If-None-Match needs no such permission. The per-resource evaluation loop is extracted into abortIfDenied so the second authorization reuses it rather than duplicating it. The class comment named floci.iam.enforcement-enabled; the key that works is floci.services.iam.enforcement-enabled. Closes #209 (cherry picked from commit 402920cf137c98f45283ad093f3df97807bb1dc7) * fix(iam): authorize an object-tag condition against the version the request names Review follow-ups on #3946. s3:ExistingObjectTag was read from the current version whatever the request asked for, so an allow conditioned on a tag decided a versioned read against tags the older version does not carry, letting it through. The lookup now passes the versionId query parameter, via a new S3Service.getObjectTagging overload that takes one. A malformed x-amz-tagging value such as "a=%zz" threw IllegalArgumentException out of URLDecoder inside the filter, answering 500 where S3 returns 400 InvalidTag. An undecodable pair is now dropped, so the policy decides. Documents both condition keys under "Condition keys floci populates" in docs/services/iam.md, including which actions receive them, the If-Match coupling, and that s3:RequestObjectTagKeys is not populated. Replaces the two var declarations in the new test with explicit types, and drops the downstream project's name from the comments and test fixtures.
This commit is contained in:
1 parent
ecdc9ccfdd
commit
09b1dc0803
6 files changed
+450
-3
No files matched your search
@@ -468,6 +468,21 @@ floci populates:
|
||||
`ResourceId.N` or `InstanceId.N`), and for `s3:GetBucketTagging`, `s3:DeleteBucketTagging`
|
||||
and `s3:DeleteBucket` (the bucket). A request naming several EC2 resources is evaluated
|
||||
once per resource and denied when any of them fails the condition, as on AWS.
|
||||
- `s3:ExistingObjectTag/<key>`: the tags already on the target object version, for
|
||||
`s3:GetObject`, `s3:GetObjectTagging`, `s3:GetObjectAcl`, `s3:PutObjectAcl`,
|
||||
`s3:DeleteObjectTagging` and `s3:PutObjectTagging`. A `versionId` in the request selects the
|
||||
version whose tags are read. **`s3:DeleteObject` and `s3:PutObject` do not receive this key**, as measured on AWS.
|
||||
An allow conditioned on it denies the delete of a correctly tagged object, and a create cannot
|
||||
be gated on tags an object does not have yet.
|
||||
- `s3:RequestObjectTag/<key>`: a tag the request asks to attach. `s3:PutObject` reads these
|
||||
from the `x-amz-tagging` header and `s3:PutObjectTagging` from the `<Tagging>` body. Any pair
|
||||
that does not decode is dropped, so a policy conditioned on the key denies such a request. Where
|
||||
enforcement lets it through, the handler still answers a malformed header with
|
||||
`400 InvalidTag`. `s3:RequestObjectTagKeys` is **not** populated, so a condition on it never
|
||||
matches.
|
||||
- A `PutObject` carrying `If-Match` is authorized as `s3:GetObject` as well, and that second
|
||||
check is made without the object's tags in the context, as measured on AWS. `If-None-Match`
|
||||
needs no such permission.
|
||||
- `aws:PrincipalArn`: the caller's ARN, resolved from the signing access key. It is the
|
||||
IAM-user ARN for a user access key, the assumed-role ARN for an STS session, and
|
||||
`arn:aws:iam::<account>:root` for the bare account-id key (floci's account-root principal),
|
||||
|
||||
+130
@@ -51,6 +51,8 @@ public class IamConditionContextResolver {
|
||||
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
|
||||
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
|
||||
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
|
||||
public static final String EXISTING_OBJECT_TAG_PREFIX = "s3:ExistingObjectTag/";
|
||||
public static final String REQUEST_OBJECT_TAG_PREFIX = "s3:RequestObjectTag/";
|
||||
|
||||
private final Instance<DynamoDbService> dynamoDbService;
|
||||
private final Instance<Ec2Service> ec2Service;
|
||||
@@ -124,10 +126,138 @@ public class IamConditionContextResolver {
|
||||
case "s3:PutBucketTagging" -> s3PutBucketTaggingConditionContext(ctx);
|
||||
case "s3:GetBucketTagging", "s3:DeleteBucketTagging", "s3:DeleteBucket" ->
|
||||
s3BucketResourceTagConditionContext(ctx);
|
||||
// Object tags. Which action is given which key is what real AWS was measured to do,
|
||||
// not what reads naturally: s3:DeleteObject is given neither key, and s3:PutObject is
|
||||
// given the tags of the REQUEST only, never those of an object it is about to
|
||||
// overwrite. See S3ObjectTagConditionEnforcementIntegrationTest.
|
||||
//
|
||||
// s3:GetObjectVersion is deliberately absent. IamActionRegistry authorizes a GET
|
||||
// carrying ?versionId= as s3:GetObject, and IamEnforcementFilter is the only caller
|
||||
// of resolve, so an arm for it would never be reached. The versionId is read from the
|
||||
// request instead, below.
|
||||
case "s3:GetObject", "s3:GetObjectTagging", "s3:GetObjectAcl",
|
||||
"s3:PutObjectAcl", "s3:DeleteObjectTagging" -> s3ExistingObjectTagConditionContext(ctx);
|
||||
case "s3:PutObject" -> s3RequestObjectTagConditionContext(ctx);
|
||||
case "s3:PutObjectTagging" -> merge(s3ExistingObjectTagConditionContext(ctx),
|
||||
s3PutObjectTaggingBodyConditionContext(ctx));
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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
|
||||
* does not match and an allow conditioned on it does not apply.
|
||||
*
|
||||
* <p>The {@code versionId} query parameter decides which version is read. Falling back to the
|
||||
* current version would authorize a read of an older version against tags it does not carry,
|
||||
* which lets a request through that the policy refuses.
|
||||
*/
|
||||
private Map<String, List<String>> s3ExistingObjectTagConditionContext(ContainerRequestContext ctx) {
|
||||
if (ctx.getUriInfo() == null || !s3Service.isResolvable()) {
|
||||
return null;
|
||||
}
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
String bucket = s3BucketName(path);
|
||||
String key = s3ObjectKey(path);
|
||||
if (bucket == null || key == null) {
|
||||
return null;
|
||||
}
|
||||
String versionId = ctx.getUriInfo().getQueryParameters().getFirst("versionId");
|
||||
Map<String, String> tags;
|
||||
try {
|
||||
tags = s3Service.get().getObjectTagging(bucket, key, versionId);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv(e, "Could not read object tags for the IAM condition context: {0}/{1} version {2}",
|
||||
bucket, key, versionId);
|
||||
return null;
|
||||
}
|
||||
if (tags == null || tags.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
tags.forEach((k, v) -> conditions.put(EXISTING_OBJECT_TAG_PREFIX + k, List.of(v)));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code s3:RequestObjectTag/<key>} from a PutObject's {@code x-amz-tagging} header, which the
|
||||
* S3 model documents as a URL query parameter encoding of the tag-set.
|
||||
*/
|
||||
private Map<String, List<String>> s3RequestObjectTagConditionContext(ContainerRequestContext ctx) {
|
||||
String header = ctx.getHeaderString("x-amz-tagging");
|
||||
if (header == null || header.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
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));
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/** {@code s3:RequestObjectTag/<key>} from the {@code <Tagging>} XML body of PutObjectTagging. */
|
||||
private Map<String, List<String>> s3PutObjectTaggingBodyConditionContext(ContainerRequestContext ctx) {
|
||||
byte[] body = bufferEntity(ctx);
|
||||
if (body == null || body.length == 0) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> tags = XmlParser.extractPairs(
|
||||
new String(body, StandardCharsets.UTF_8), "Tag", "Key", "Value");
|
||||
if (tags.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
tags.forEach((k, v) -> conditions.put(REQUEST_OBJECT_TAG_PREFIX + k, List.of(v)));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> merge(Map<String, List<String>> a, Map<String, List<String>> b) {
|
||||
if (a == null) {
|
||||
return b;
|
||||
}
|
||||
if (b == null) {
|
||||
return a;
|
||||
}
|
||||
Map<String, List<String>> merged = new LinkedHashMap<>(a);
|
||||
merged.putAll(b);
|
||||
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;
|
||||
int slash = stripped.indexOf('/');
|
||||
if (slash < 0 || slash == stripped.length() - 1) {
|
||||
return null;
|
||||
}
|
||||
return stripped.substring(slash + 1);
|
||||
}
|
||||
|
||||
Map<String, List<String>> s3BucketListConditionContext(MultivaluedMap<String, String> queryParameters) {
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
addQueryCondition(conditions, "s3:prefix", queryParameters, "prefix");
|
||||
|
||||
@@ -34,7 +34,8 @@ import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* JAX-RS filter that enforces IAM policies on every incoming request when
|
||||
* {@code floci.iam.enforcement-enabled = true}.
|
||||
* {@code floci.services.iam.enforcement-enabled = true}
|
||||
* ({@code FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true} in the environment).
|
||||
*
|
||||
* <p>Bypass rules (request is always allowed through):
|
||||
* <ul>
|
||||
@@ -236,6 +237,31 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
targetContexts.add(targetContext);
|
||||
}
|
||||
|
||||
if (abortIfDenied(ctx, caller, action, credentialScope, resources, targetContexts,
|
||||
region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A PutObject carrying If-Match compares against the object it replaces, and S3 authorizes
|
||||
// that read as s3:GetObject, WITHOUT the object's tags in the request context. Measured
|
||||
// against real AWS: under a GetObject allow conditioned on s3:ExistingObjectTag the
|
||||
// conditional write is AccessDenied, under a GetObject allow scoped by prefix alone it
|
||||
// succeeds, and with no GetObject at all it is denied. If-None-Match needs no such
|
||||
// permission.
|
||||
if ("s3:PutObject".equals(action) && ctx.getHeaderString("If-Match") != null) {
|
||||
abortIfDenied(ctx, caller, "s3:GetObject", credentialScope, resources,
|
||||
withoutObjectTags(targetContexts), region, accountId, akid);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates one action against every resource and target context, aborting the request with
|
||||
* AccessDenied on the first DENY. Returns true when the request was aborted.
|
||||
*/
|
||||
private boolean abortIfDenied(ContainerRequestContext ctx, CallerContext caller, String action,
|
||||
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();
|
||||
@@ -267,9 +293,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
+ " because no identity-based policy allows the " + action + " action";
|
||||
emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);
|
||||
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resource));
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The same contexts with every object-tag key removed, keeping the principal and global keys. */
|
||||
private static List<Map<String, List<String>>> withoutObjectTags(
|
||||
List<Map<String, List<String>>> targetContexts) {
|
||||
List<Map<String, List<String>>> stripped = new ArrayList<>();
|
||||
for (Map<String, List<String>> targetContext : targetContexts) {
|
||||
if (targetContext == null) {
|
||||
stripped.add(null);
|
||||
continue;
|
||||
}
|
||||
Map<String, List<String>> copy = new HashMap<>(targetContext);
|
||||
copy.keySet().removeIf(key ->
|
||||
key.startsWith(IamConditionContextResolver.EXISTING_OBJECT_TAG_PREFIX)
|
||||
|| key.startsWith(IamConditionContextResolver.REQUEST_OBJECT_TAG_PREFIX));
|
||||
stripped.add(copy.isEmpty() ? null : copy);
|
||||
}
|
||||
return stripped;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2003,7 +2003,12 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
public Map<String, String> getObjectTagging(String bucketName, String key) {
|
||||
S3Object obj = getStoredObject(bucketName, key, null);
|
||||
return getObjectTagging(bucketName, key, null);
|
||||
}
|
||||
|
||||
/** Tags of one version, or of the current version when {@code versionId} is null or "null". */
|
||||
public Map<String, String> getObjectTagging(String bucketName, String key, String versionId) {
|
||||
S3Object obj = getStoredObject(bucketName, key, "null".equals(versionId) ? null : versionId);
|
||||
return obj.getTags() != null ? obj.getTags() : Map.of();
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -138,6 +138,10 @@ class IamConditionContextResolverTest {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
assertNull(resolver.resolve("lambda", "lambda:InvokeFunction", containerRequest));
|
||||
// s3:DeleteObject is unsupported on purpose: real AWS gives it no object-tag keys, so a
|
||||
// delete conditioned on s3:ExistingObjectTag is denied.
|
||||
assertNull(resolver.resolve("s3", "s3:DeleteObject", containerRequest));
|
||||
// A supported object action with nothing to read tags from offers no keys either.
|
||||
assertNull(resolver.resolve("s3", "s3:GetObject", containerRequest));
|
||||
}
|
||||
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@code s3:ExistingObjectTag/<key>} and {@code s3:RequestObjectTag/<key>} under IAM enforcement.
|
||||
*
|
||||
* <p>Every expectation here is a row measured against real AWS (us-east-2, 2026-09-18, an IAM user
|
||||
* whose only policy was the statement under test, each policy proven live before it was tested).
|
||||
* Two of the rows are not what the documentation alone would lead you to write, and they are the
|
||||
* reason this test states its provenance:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code s3:DeleteObject} is NOT given {@code s3:ExistingObjectTag}. An allow conditioned on it
|
||||
* denies the delete of a correctly tagged object.</li>
|
||||
* <li>A {@code PutObject} carrying {@code If-Match} is also authorized as {@code s3:GetObject}, and
|
||||
* that check is made WITHOUT the object's tags: with a tag-conditioned GetObject allow the
|
||||
* conditional write is denied, with a prefix-scoped one it is allowed.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Before this, neither key was resolved at all, so a statement conditioned on one never matched
|
||||
* and everything was denied - including what AWS allows.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(S3ObjectTagConditionEnforcementIntegrationTest.IamEnforcementProfile.class)
|
||||
class S3ObjectTagConditionEnforcementIntegrationTest {
|
||||
|
||||
private static final String ADMIN = "test";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private static final String EXISTING_A = "\"Condition\":{\"StringEquals\":{\"s3:ExistingObjectTag/env\":\"a\"}}";
|
||||
private static final String REQUEST_A = "\"Condition\":{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"a\"}}";
|
||||
|
||||
@Test
|
||||
void existingObjectTagGatesReads() {
|
||||
Fixture f = new Fixture("read");
|
||||
// Control: with no policy at all the user is denied, so enforcement is on.
|
||||
assertEquals(403, f.get("a/tagged-a"));
|
||||
|
||||
f.policy(allow("s3:GetObject", f.objects(), EXISTING_A));
|
||||
assertEquals(200, f.get("a/tagged-a"), "own tag");
|
||||
assertEquals(403, f.get("a/tagged-b"), "a foreign tag");
|
||||
assertEquals(403, f.get("a/untagged"), "no tag at all: StringEquals on an absent key does not match");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestObjectTagGatesWritesAndExistingObjectTagCannot() {
|
||||
Fixture f = new Fixture("write");
|
||||
f.policy(allow("\"s3:PutObject\",\"s3:PutObjectTagging\"", f.objects(), REQUEST_A));
|
||||
assertEquals(200, f.put("a/new-1", "env=a", null), "first create, tagged for this environment");
|
||||
assertEquals(200, f.put("a/new-2", "env=a&owner=aws_thing.x", null), "extra tags beside it");
|
||||
assertEquals(403, f.put("a/new-3", null, null), "untagged");
|
||||
assertEquals(403, f.put("a/new-4", "env=b", null), "tagged for another environment");
|
||||
|
||||
// The policy that reviews correctly and bricks a new environment: a create cannot be gated on
|
||||
// the tags of an object that does not exist yet.
|
||||
f.policy(allow("\"s3:PutObject\",\"s3:PutObjectTagging\"", f.objects(), EXISTING_A));
|
||||
assertEquals(403, f.put("a/brand-new", "env=a", null), "ExistingObjectTag alone locks out the first write");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteIsNotGivenTheExistingObjectTag() {
|
||||
Fixture f = new Fixture("delete");
|
||||
f.policy(allow("s3:DeleteObject", f.objects(), EXISTING_A));
|
||||
assertEquals(403, f.delete("a/tagged-a"), "measured on AWS: a tag-conditioned delete is denied even for a correctly tagged object");
|
||||
|
||||
f.policy(allow("s3:DeleteObject", f.objects(), null));
|
||||
assertEquals(204, f.delete("a/tagged-a"), "scoped by prefix alone it is allowed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConditionalWriteAlsoNeedsGetObjectWithoutTheTags() {
|
||||
Fixture f = new Fixture("cas");
|
||||
String write = allow("\"s3:PutObject\",\"s3:PutObjectTagging\"", f.objects(), REQUEST_A);
|
||||
|
||||
f.policy(write + "," + allow("s3:GetObject", f.objects(), EXISTING_A));
|
||||
String etag = f.etag("a/tagged-a");
|
||||
assertEquals(200, f.put("a/tagged-a", "env=a", null), "an overwrite with no precondition");
|
||||
etag = f.etag("a/tagged-a");
|
||||
assertEquals(403, f.put("a/tagged-a", "env=a", etag), "If-Match under a tag-conditioned GetObject");
|
||||
|
||||
f.policy(write + "," + allow("s3:GetObject", f.objects(), null));
|
||||
assertEquals(200, f.put("a/tagged-a", "env=a", etag), "If-Match under a prefix-scoped GetObject");
|
||||
|
||||
f.policy(write);
|
||||
etag = f.etag("a/tagged-a");
|
||||
assertEquals(403, f.put("a/tagged-a", "env=a", etag), "If-Match with no GetObject at all");
|
||||
assertEquals(200, f.put("a/created", "env=a", "*none*"), "If-None-Match needs no GetObject");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyOnAForeignTagCatchesAMisScopedPrefixForReadsOnly() {
|
||||
Fixture f = new Fixture("deny");
|
||||
// The allow is deliberately too wide: both environments' prefixes.
|
||||
f.policy(allow("\"s3:GetObject\",\"s3:DeleteObject\"", f.objects(), null) + ","
|
||||
+ allow("\"s3:PutObject\",\"s3:PutObjectTagging\"", f.objects(), REQUEST_A) + ","
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":[\"s3:GetObject\",\"s3:DeleteObject\",\"s3:PutObject\"],\"Resource\":\"" + f.objects() + "\","
|
||||
+ "\"Condition\":{\"StringNotEquals\":{\"s3:ExistingObjectTag/env\":\"a\"},\"Null\":{\"s3:ExistingObjectTag/env\":\"false\"}}}");
|
||||
assertEquals(200, f.get("a/tagged-a"), "own object");
|
||||
assertEquals(403, f.get("b/theirs"), "the neighbour's object: the tag still denies the read");
|
||||
assertEquals(200, f.get("a/untagged"), "an untagged object is readable under this shape");
|
||||
assertEquals(200, f.put("a/tagged-a", "env=a", f.etag("a/tagged-a")), "the CAS write works");
|
||||
assertEquals(200, f.put("b/theirs", "env=a", null), "measured on AWS: overwriting the neighbour is NOT caught by its tag");
|
||||
assertEquals(204, f.delete("b/theirs-2"), "measured on AWS: deleting the neighbour is NOT caught by its tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOlderVersionIsAuthorizedAgainstItsOwnTags() {
|
||||
Fixture f = new Fixture("version");
|
||||
f.versioning();
|
||||
// Two versions of one key with different tags. The current version carries the tag the
|
||||
// policy allows; the one under it does not.
|
||||
String denied = f.seedVersion("a/rolled", "env=b");
|
||||
f.seedVersion("a/rolled", "env=a");
|
||||
|
||||
f.policy(allow("s3:GetObject", f.objects(), EXISTING_A));
|
||||
assertEquals(200, f.get("a/rolled"), "the current version carries the allowed tag");
|
||||
assertEquals(403, f.getVersion("a/rolled", denied),
|
||||
"the older version carries a foreign tag, so its own tags decide");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUndecodableTaggingHeaderIsRejectedNotThrown() {
|
||||
Fixture f = new Fixture("badtag");
|
||||
f.policy(allow("\"s3:PutObject\",\"s3:PutObjectTagging\"", f.objects(), REQUEST_A));
|
||||
// "%zz" is not a valid escape. The pair carries no usable condition key, so the request
|
||||
// is refused by the policy rather than escaping the filter as a 500.
|
||||
assertEquals(403, f.put("a/bad", "env=%zz", null), "an undecodable value");
|
||||
assertEquals(403, f.put("a/bad", "%zz=a", null), "an undecodable key");
|
||||
}
|
||||
|
||||
private static String allow(String actions, String resource, String condition) {
|
||||
String action = actions.startsWith("\"") ? "[" + actions + "]" : "\"" + actions + "\"";
|
||||
return "{\"Effect\":\"Allow\",\"Action\":" + action + ",\"Resource\":\"" + resource + "\""
|
||||
+ (condition == null ? "" : "," + condition) + "}";
|
||||
}
|
||||
|
||||
/** One bucket, a few tagged objects seeded as the admin, and one IAM user with an access key. */
|
||||
private static final class Fixture {
|
||||
final String bucket;
|
||||
final String user;
|
||||
final String accessKeyId;
|
||||
|
||||
Fixture(String name) {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
bucket = "objtag-" + name + "-" + suffix;
|
||||
user = "objtag-" + name + "-" + suffix;
|
||||
given().header("Authorization", auth(ADMIN, "s3")).when().put("/" + bucket).then().statusCode(200);
|
||||
seed("a/tagged-a", "env=a");
|
||||
seed("a/tagged-b", "env=b");
|
||||
seed("a/untagged", null);
|
||||
seed("b/theirs", "env=b");
|
||||
seed("b/theirs-2", "env=b");
|
||||
given().formParam("Action", "CreateUser").formParam("UserName", user)
|
||||
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200);
|
||||
accessKeyId = given().formParam("Action", "CreateAccessKey").formParam("UserName", user)
|
||||
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
String objects() {
|
||||
return "arn:aws:s3:::" + bucket + "/*";
|
||||
}
|
||||
|
||||
void seed(String key, String tagging) {
|
||||
RequestSpecification req = given().header("Authorization", auth(ADMIN, "s3")).body("seed");
|
||||
if (tagging != null) {
|
||||
req = req.header("x-amz-tagging", tagging);
|
||||
}
|
||||
req.when().put("/" + bucket + "/" + key).then().statusCode(200);
|
||||
}
|
||||
|
||||
void versioning() {
|
||||
given().header("Authorization", auth(ADMIN, "s3"))
|
||||
.body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
|
||||
.queryParam("versioning", "")
|
||||
.when().put("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
/** Writes one version of a key as the admin and returns its version id. */
|
||||
String seedVersion(String key, String tagging) {
|
||||
return given().header("Authorization", auth(ADMIN, "s3")).body("seed")
|
||||
.header("x-amz-tagging", tagging)
|
||||
.when().put("/" + bucket + "/" + key).then().statusCode(200)
|
||||
.extract().header("x-amz-version-id");
|
||||
}
|
||||
|
||||
int getVersion(String key, String versionId) {
|
||||
return given().header("Authorization", auth(accessKeyId, "s3"))
|
||||
.queryParam("versionId", versionId)
|
||||
.when().get("/" + bucket + "/" + key).statusCode();
|
||||
}
|
||||
|
||||
void policy(String statements) {
|
||||
given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
|
||||
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")
|
||||
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
int get(String key) {
|
||||
return given().header("Authorization", auth(accessKeyId, "s3")).when().get("/" + bucket + "/" + key).statusCode();
|
||||
}
|
||||
|
||||
int delete(String key) {
|
||||
return given().header("Authorization", auth(accessKeyId, "s3")).when().delete("/" + bucket + "/" + key).statusCode();
|
||||
}
|
||||
|
||||
String etag(String key) {
|
||||
return given().header("Authorization", auth(ADMIN, "s3")).when().head("/" + bucket + "/" + key)
|
||||
.then().statusCode(200).extract().header("ETag");
|
||||
}
|
||||
|
||||
/** ifMatch: null for none, "*none*" for If-None-Match: *, anything else is the If-Match value. */
|
||||
int put(String key, String tagging, String ifMatch) {
|
||||
RequestSpecification req = given().header("Authorization", auth(accessKeyId, "s3")).body("written");
|
||||
if (tagging != null) {
|
||||
req = req.header("x-amz-tagging", tagging);
|
||||
}
|
||||
if ("*none*".equals(ifMatch)) {
|
||||
req = req.header("If-None-Match", "*");
|
||||
} else if (ifMatch != null) {
|
||||
req = req.header("If-Match", ifMatch);
|
||||
}
|
||||
return req.when().put("/" + bucket + "/" + key).statusCode();
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260629/" + REGION + "/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
|
||||
public static final class IamEnforcementProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.iam.enforcement-enabled", "true");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user