fix(s3): evaluate identity policies per key in DeleteObjects (#5471)

* fix(s3): evaluate identity policies per key in DeleteObjects

Under IAM enforcement a batch DeleteObjects now honours the caller's
identity policies for every key it names, so a user allowed to delete
under one prefix can no longer empty the rest of the bucket in one
request. As in S3, the request still answers 200 and each denied key
comes back as an AccessDenied error with the message "Access Denied",
while the allowed keys are deleted.

IamEnforcementFilter cannot do this on its own: S3 has no
s3:DeleteObjects action, the keys arrive only in the request body, and
the outcome is per key rather than per request. S3Controller therefore
authorizes each entry through authorizeAdditionalResource before the
existing bucket-policy checks, the way CopyObject authorizes its source:
s3:DeleteObject, or s3:DeleteObjectVersion for an entry naming a
version, plus s3:GetObject for an ETag-conditioned entry, matching the
single-key conditional delete. The credential comes from the header or
the presigned query string, and no resource-policy decision is passed,
so the bucket policy is resolved with the same global condition keys
the filter uses for a single-key delete.

authorizeAdditionalResource now canonicalises the credential scope as
filter() does, so an s3express-signed request finds the S3 bucket
policy instead of none.

* fix(s3): close the remaining DeleteObjects identity-check gaps

A batch DeleteObjects now applies the caller's IAM policies to every key
however the request is signed and whichever service it was signed for,
and a governance-retention bypass now needs the bypass permission from
those policies too.

A presigned request that also sends an empty Authorization header is
evaluated with its query credential. IamEnforcementFilter.filter()
already treats a blank header as absent; the handler passed it through,
found no access key in it and skipped every per-key check.

When an entry is under active GOVERNANCE retention and the request asks
to bypass it, s3:BypassGovernanceRetention is evaluated through the same
per-key IAM path as the delete, with the same "Access Denied" error,
before the existing bucket-policy check. The single-key DeleteObject
path is unchanged.

authorizeAdditionalResource now picks resource-policy providers by the
service of the action being authorized, as filter() picks them by the
route's serving service, instead of by the caller's signing scope. A
request signed for another service, or for the s3express alias, now
sees the bucket policy. The canonicalised signing scope still selects
the error codes for an inactive key or expired session.

S3ResourcePolicyProvider is the only registered ResourcePolicyProvider,
so the other callers of the helper see no change: CopyObject's source
read passes its own resource-policy decision and never resolves
providers, and SecretsManager rotation (lambda:InvokeFunction) and SSM
secret references (secretsmanager:GetSecretValue) find no provider
under either scope. A presigned POST's s3:PutObject check changes only
for a form credential not scoped to s3, which now sees the bucket
policy like any other S3 request.

* fix(s3): check governance bypass for the null version in DeleteObjects

A DeleteObjects entry naming VersionId "null" under active GOVERNANCE
retention now needs s3:BypassGovernanceRetention before the bypass
header lets it through, as an entry naming any other version does.

isGovernanceRetentionActive looked the literal "null" up as a versioned
key, found nothing and reported the entry as unprotected, so the batch
path skipped both bypass checks (IAM and bucket policy). Deletion
treats "null" as the unversioned object at the plain key, the object
written before versioning was enabled. The helper now resolves it the
same way. DeleteObjects is its only caller.

The batch path evaluates identity policies for every key of a request
whose credential IAM knows. An unknown or unreadable credential with S3
request authentication off is handled as an unsigned request, as
filter() handles it; with S3 authentication on, S3 refuses an unknown
key. The comments in IamEnforcementFilter now say that DeleteObjects
reaches authorizeAdditionalResource with a key filter() has not
checked, since filter() returns before its key checks on a route no
action maps.

Tests: the null-version bypass, a mixed batch where only the retained
entry needs the bypass permission, and an inactive key and an expired
session signed for s3express answered with S3's InvalidAccessKeyId and
ExpiredToken rather than the other services' codes.

* test(s3): pin the null-version lookup to the pre-versioning object

A DeleteObjects entry naming VersionId null resolves to the object at the
plain key only when that object has no version id. On a versioning-enabled
bucket whose current version is GOVERNANCE-retained and versioned, a null
entry names a version that does not exist, so it must not demand
s3:BypassGovernanceRetention: S3 reports it deleted and the retained version
stays. The test fails if the version-id filter in isGovernanceRetentionActive
is dropped.

* fix(s3): name the version in each DeleteObjects error

An entry that names a VersionId now reports it in its <Error>, as S3 does,
so a batch naming several versions of one key says which of them failed.
This covers both the per-key authorization errors and the errors from the
delete itself (retention, precondition). An entry naming no version still
reports none.

* test(s3): pin the VersionId on a DeleteObjects error from the delete itself

A retained version deleted without the bypass header is refused by the
retention, not the authorization check, and that error names the version too.

* test(s3): create DeleteObjects test users through EnforcementFixtures

The two DeleteObjects enforcement classes carried their own copies of the
createUser and auth helpers that several S3 and IAM enforcement tests already
repeat. EnforcementFixtures now provides both: createUser registers removeUser
with PartitionCleanup before it creates the user, so the users and access keys
these classes make no longer outlive them in the shared application.
This commit is contained in:
TiM authored and GitHub committed 2026-10-11 22:18:53 -04:00
1 parent da063a82f8
commit 23c6666a51
6 files changed
+837 -40

No files matched your search

@@ -845,21 +845,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (akid == null || "test".equals(akid)) {
return;
}
String credentialScope = extractCredentialScope(authorizationHeader);
if (credentialScope == null) {
String rawScope = extractCredentialScope(authorizationHeader);
if (rawScope == null) {
return;
}
// Canonicalised as filter() does, so a signing alias (s3express) is refused below with its
// canonical service's (s3) error codes.
String credentialScope = catalog.canonicalCredentialScope(rawScope);
String accountId = resolveCredentialAccountId(akid, authorizationHeader);
String previousAccountId = requestContext.getAccountId();
requestContext.setAccountId(accountId);
try {
// A presigned POST carries its credential only in the form body, which filter() never
// sees, so a key IAM holds but that can no longer be used is refused here as filter()
// refuses it. Otherwise an inactive key would act with its user's policies, and
// resolveCallerContext would delete an expired session, which would then read as a key
// that exists nowhere. For a second resource of a request filter() has seen, the key
// has already passed these checks.
// A key IAM holds but that can no longer be used is refused here as filter() refuses it,
// for the requests whose key filter() has not checked: a presigned POST, whose credential
// is only in the form body, and DeleteObjects, a route no action maps, where filter()
// returns before its key checks. Otherwise an inactive key would act with its user's
// policies, and resolveCallerContext would delete an expired session, which would then
// read as a key that exists nowhere. For a second resource of a request filter() has
// authorized, the key has already passed these checks.
boolean accountRootKey = akid.equals(accountId);
if (!accountRootKey && iamService.isInactiveAccessKey(akid)) {
throw unrecognizedClientException(credentialScope);
@@ -877,13 +881,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid, now);
if (caller == null) {
// No unknown-key rejection here, unlike filter(), and none is needed. For a second
// resource of a request filter() has seen (CopyObject's source, RotateSecret's
// rotation function, the secrets behind SSM GetParameter) the credential is the one
// filter() evaluated, and filter() refuses an unknown key before the handler runs. A
// presigned POST carries its credential only in the form body, which filter() never
// sees: an unknown key there is refused by S3's presigned-POST signature check when
// S3 auth enforcement is on, and otherwise uploads as an unsigned request would.
// No unknown-key rejection here, unlike filter(). For a second resource of a request
// filter() has authorized (CopyObject's source, RotateSecret's rotation function, the
// secrets behind SSM GetParameter) the credential is the one filter() evaluated, and
// filter() refuses an unknown key before the handler runs. Two callers reach here with
// a key filter() has not checked: a presigned POST, whose credential is only in the
// form body, and DeleteObjects, where filter() returns before its key checks because
// no action maps the route. For both, S3's own request authentication refuses an
// unknown key when S3 auth enforcement is on; with it off, the request proceeds as an
// unsigned one would.
if (scpLevels == null || !accountRootKey) {
return;
}
@@ -908,8 +914,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String effectiveOwnerAccountId = resourceOwnerAccountId;
List<String> policyDocs = null;
if (effectiveDecision == null) {
// Resource policies belong to the service that owns the resource, which is the action's
// service, not whichever service the caller signed for. filter() picks them by the route's
// serving service for the same reason; a credential scoped to another service, or to a
// signing alias such as s3express, would otherwise see no bucket policy at all.
String resourcePolicyScope = catalog.canonicalCredentialScope(action.split(":", 2)[0]);
List<ResourcePolicyProvider.ResourcePolicy> resourcePolicies = resolveResourcePolicies(
credentialScope, resource);
resourcePolicyScope, resource);
effectiveOwnerAccountId = resourcePolicies.isEmpty()
? null : resourcePolicies.getFirst().ownerAccountId();
policyDocs = resourcePolicies.stream()
@@ -1607,20 +1607,33 @@ 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());
List<XmlParser.KeyVersion> authorizedEntries = new ArrayList<>();
List<S3Service.DeleteError> authorizationErrors = new ArrayList<>();
for (XmlParser.KeyVersion entry : entries) {
try {
authorizeDeleteEntryIdentity(iamCredential, bucket, entry);
s3Service.authorizeDeleteObject(bucket, entry.key(), entry.versionId(), authorization);
authorizeDeleteETagRead(bucket, entry.key(), entry.eTag(), authorization);
if (bypass && s3Service.isGovernanceRetentionActive(
bucket, entry.key(), entry.versionId())) {
// The bypass is a permission of its own, so IAM evaluates it against the caller's
// policies as it does the delete, not only the bucket-policy check that follows.
authorizeEntryIdentity(iamCredential, "s3:BypassGovernanceRetention", bucket, entry.key());
s3Service.authorizeObjectWrite(bucket, entry.key(),
"s3:BypassGovernanceRetention", authorization);
}
authorizedEntries.add(entry);
} catch (AwsException e) {
authorizationErrors.add(new S3Service.DeleteError(entry.key(), e.getErrorCode(), e.getMessage()));
authorizationErrors.add(new S3Service.DeleteError(
entry.key(), entry.versionId(), e.getErrorCode(), e.getMessage()));
}
}
@@ -1645,37 +1658,77 @@ public class S3Controller {
}
}
for (S3Service.DeleteError e : authorizationErrors) {
builder.start("Error")
.elem("Key", e.key())
.elem("Code", e.code())
.elem("Message", e.message())
.end("Error");
appendDeleteError(builder, e);
}
for (S3Service.DeleteError e : result.errors()) {
builder.start("Error")
.elem("Key", e.key())
.elem("Code", e.code())
.elem("Message", e.message())
.end("Error");
appendDeleteError(builder, e);
}
builder.end("DeleteResult");
return Response.ok(builder.build()).type(MediaType.APPLICATION_XML).build();
}
// An entry naming a version reports it back, so a batch naming several versions of one key
// says which of them failed.
private static void appendDeleteError(XmlBuilder builder, S3Service.DeleteError error) {
builder.start("Error").elem("Key", error.key());
if (error.versionId() != null) {
builder.elem("VersionId", error.versionId());
}
builder.elem("Code", error.code())
.elem("Message", error.message())
.end("Error");
}
// A conditional delete against an ETag reveals whether the object still has it, so S3 requires
// s3:GetObject as well as s3:DeleteObject. The existence check (If-Match: *) needs only the delete.
private void authorizeDeleteETagRead(String bucket, String key, String ifMatch,
S3Service.RequestAuthorization authorization) {
if (ifMatch == null) {
return;
}
String value = ifMatch.trim();
if (value.equals("*") || value.equals("\"*\"")) {
if (!isETagCondition(ifMatch)) {
return;
}
s3Service.authorizeGetObject(bucket, key, null, authorization);
}
private static boolean isETagCondition(String ifMatch) {
if (ifMatch == null) {
return false;
}
String value = ifMatch.trim();
return !value.equals("*") && !value.equals("\"*\"");
}
/**
* Evaluates the caller's identity policies for one DeleteObjects entry, which IamEnforcementFilter
* cannot do: S3 has no s3:DeleteObjects action, the keys arrive only in the request body, and a
* denial answers that one key with an {@code <Error>} rather than refusing the whole request.
* Each entry needs s3:DeleteObject, or s3:DeleteObjectVersion when it names a version, plus
* s3:GetObject when it carries an ETag condition.
*
* <p>No resource-policy decision is passed, so the filter resolves the bucket policy itself, with
* its own global condition keys, as it does for a single-key delete. S3's error for a denied entry
* reads "Access Denied", not the filter's message for a whole-request denial.
*/
private void authorizeDeleteEntryIdentity(String iamCredential, String bucket, XmlParser.KeyVersion entry) {
String action = entry.versionId() == null ? "s3:DeleteObject" : "s3:DeleteObjectVersion";
authorizeEntryIdentity(iamCredential, action, bucket, entry.key());
if (isETagCondition(entry.eTag())) {
authorizeEntryIdentity(iamCredential, "s3:GetObject", bucket, entry.key());
}
}
/** Evaluates one action on one DeleteObjects entry's object, answering a denial as S3 does per key. */
private void authorizeEntryIdentity(String iamCredential, String action, String bucket, String key) {
String resource = S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key);
try {
iamEnforcementFilter.authorizeAdditionalResource(iamCredential, action, resource);
} catch (AwsException e) {
if ("AccessDenied".equals(e.getErrorCode())) {
throw new AwsException("AccessDenied", "Access Denied", 403);
}
throw e;
}
}
private Response handleListParts(String bucket, String key, String uploadId,
Integer maxPartsParam, String partNumberMarkerParam) {
MultipartUpload upload = s3Service.listParts(bucket, key, uploadId);
@@ -2083,10 +2083,19 @@ public class S3Service implements Resettable, ResourceProvider {
*/
public boolean isGovernanceRetentionActive(String bucketName, String key, String versionId) {
ensureBucketExists(bucketName);
S3Object object = (versionId != null
? objectStore.get(versionedKey(bucketName, key, versionId))
: objectStore.get(objectKey(bucketName, key)))
.orElse(null);
S3Object object;
if ("null".equals(versionId)) {
// Resolved as deleteObjectLocked resolves it: the null version is the unversioned object
// at the plain key, so a versioned key named "null" would miss a retained one.
object = objectStore.get(objectKey(bucketName, key))
.filter(existing -> existing.getVersionId() == null)
.orElse(null);
} else {
object = (versionId != null
? objectStore.get(versionedKey(bucketName, key, versionId))
: objectStore.get(objectKey(bucketName, key)))
.orElse(null);
}
return object != null
&& !object.isDeleteMarker()
&& "GOVERNANCE".equals(object.getObjectLockMode())
@@ -2608,7 +2617,7 @@ public class S3Service implements Resettable, ResourceProvider {
public record DeleteResult(String key, String versionId, boolean deleteMarker, String deleteMarkerVersionId) {
}
public record DeleteError(String key, String code, String message) {
public record DeleteError(String key, String versionId, String code, String message) {
}
public record DeleteObjectsResult(List<DeleteResult> deleted, List<DeleteError> errors) {
@@ -2633,9 +2642,9 @@ public class S3Service implements Resettable, ResourceProvider {
deleted.add(new DeleteResult(entry.key(), entry.versionId(), false, null));
}
} catch (AwsException e) {
errors.add(new DeleteError(entry.key(), e.getErrorCode(), e.getMessage()));
errors.add(new DeleteError(entry.key(), entry.versionId(), e.getErrorCode(), e.getMessage()));
} catch (Exception e) {
errors.add(new DeleteError(entry.key(), "InternalError", e.getMessage()));
errors.add(new DeleteError(entry.key(), entry.versionId(), "InternalError", e.getMessage()));
}
}
return new DeleteObjectsResult(deleted, errors);
@@ -0,0 +1,517 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
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;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DeleteObjects is authorized per object, as S3 does it: there is no {@code s3:DeleteObjects}
* action, so each entry needs {@code s3:DeleteObject} (or {@code s3:DeleteObjectVersion} for an
* entry naming a version) on its own key, and a denied entry comes back as an {@code AccessDenied}
* {@code <Error>} in a 200 response while the allowed entries are deleted. The DeleteObjects API
* reference's mixed success/error example is the shape asserted here.
*
* <p>Only IAM enforcement is on, so S3's own bucket-policy evaluation does not run and every
* decision below comes from the IAM layer, bucket policies included.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
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);
@Inject
IamService iamService;
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void anIdentityPolicyOnOnePrefixDeletesOnlyThatPrefix() {
String bucket = bucket("delobj-prefix");
put(bucket, "allowed/a.txt");
put(bucket, "protected/b.txt");
String user = uniqueName("delobj-prefix");
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/allowed/*"));
XmlPath result = deleteObjects(accessKeyId, "s3", bucket, false, entry("allowed/a.txt"), entry("protected/b.txt"));
assertEquals(List.of("allowed/a.txt"), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "protected/b.txt");
assertEquals(List.of(), result.getList("DeleteResult.Error.VersionId"),
"an entry naming no version reports none");
assertGone(bucket, "allowed/a.txt");
assertPresent(bucket, "protected/b.txt");
}
@Test
void quietModeStillReportsTheDeniedKey() {
String bucket = bucket("delobj-quiet");
put(bucket, "allowed/a.txt");
put(bucket, "protected/b.txt");
String user = uniqueName("delobj-quiet");
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/allowed/*"));
XmlPath result = deleteObjects(accessKeyId, "s3", bucket, true, entry("allowed/a.txt"), entry("protected/b.txt"));
assertEquals(List.of(), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "protected/b.txt");
assertGone(bucket, "allowed/a.txt");
assertPresent(bucket, "protected/b.txt");
}
@Test
void anEntryNamingAVersionNeedsDeleteObjectVersion() {
String bucket = bucket("delobj-version");
enableVersioning(bucket);
String olderVersionId = put(bucket, "versioned.txt");
String versionId = put(bucket, "versioned.txt");
String user = uniqueName("delobj-version");
String accessKeyId = createUser(user);
String objects = "arn:aws:s3:::" + bucket + "/*";
userPolicy(user, allow("s3:DeleteObject", objects));
XmlPath denied = deleteObjects(accessKeyId, "s3", bucket, false,
versionEntry("versioned.txt", olderVersionId), versionEntry("versioned.txt", versionId));
assertEquals(List.of(), denied.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("AccessDenied", "AccessDenied"), denied.getList("DeleteResult.Error.Code"));
assertEquals(List.of(olderVersionId, versionId), denied.getList("DeleteResult.Error.VersionId"),
"each error names the version it refused");
assertVersionPresent(bucket, "versioned.txt", olderVersionId);
assertVersionPresent(bucket, "versioned.txt", versionId);
userPolicy(user, allow("s3:DeleteObjectVersion", objects));
XmlPath allowed = deleteObjects(accessKeyId, "s3", bucket, false, versionEntry("versioned.txt", versionId));
assertEquals(List.of("versioned.txt"), allowed.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of(versionId), allowed.getList("DeleteResult.Deleted.VersionId"));
assertEquals(List.of(), allowed.getList("DeleteResult.Error.Key"));
}
@Test
void anETagConditionedEntryAlsoNeedsGetObject() {
String bucket = bucket("delobj-etag");
for (String key : List.of("etag.txt", "stale.txt", "star.txt", "quoted-star.txt", "padded-star.txt")) {
put(bucket, key);
}
String eTag = given().header("Authorization", auth(ADMIN, "s3")).when().head("/" + bucket + "/etag.txt")
.then().statusCode(200).extract().header("ETag");
String staleETag = "\"00000000000000000000000000000000\"";
String user = uniqueName("delobj-etag");
String accessKeyId = createUser(user);
String objects = "arn:aws:s3:::" + bucket + "/*";
userPolicy(user, allow("s3:DeleteObject", objects));
XmlPath deleteOnly = deleteObjects(accessKeyId, "s3", bucket, false,
eTagEntry("etag.txt", eTag), eTagEntry("stale.txt", staleETag),
eTagEntry("star.txt", "*"), eTagEntry("quoted-star.txt", "\"*\""),
eTagEntry("padded-star.txt", " * "));
assertEquals(List.of("star.txt", "quoted-star.txt", "padded-star.txt"),
deleteOnly.getList("DeleteResult.Deleted.Key"),
"an existence check needs only the delete");
assertEquals(List.of("etag.txt", "stale.txt"), deleteOnly.getList("DeleteResult.Error.Key"),
"an ETag condition with no GetObject is denied, before its ETag is compared");
assertEquals(List.of("AccessDenied", "AccessDenied"), deleteOnly.getList("DeleteResult.Error.Code"));
assertEquals(List.of("Access Denied", "Access Denied"), deleteOnly.getList("DeleteResult.Error.Message"));
assertPresent(bucket, "etag.txt");
assertPresent(bucket, "stale.txt");
userPolicy(user, allow(List.of("s3:DeleteObject", "s3:GetObject"), objects));
XmlPath withRead = deleteObjects(accessKeyId, "s3", bucket, false,
eTagEntry("etag.txt", eTag), eTagEntry("stale.txt", staleETag));
assertEquals(List.of("etag.txt"), withRead.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("stale.txt"), withRead.getList("DeleteResult.Error.Key"));
assertEquals(List.of("PreconditionFailed"), withRead.getList("DeleteResult.Error.Code"),
"with GetObject the condition itself is evaluated");
assertPresent(bucket, "stale.txt");
}
@Test
void aBucketPolicyGrantOnAPrefixDeletesOnlyThatPrefix() {
String bucket = bucket("delobj-bp-grant");
put(bucket, "shared/a.txt");
put(bucket, "private/b.txt");
String user = uniqueName("delobj-bp-grant");
String accessKeyId = createUser(user);
bucketPolicy(bucket, """
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:user/%s"},
"Action":"s3:DeleteObject","Resource":"arn:aws:s3:::%s/shared/*"}""".formatted(ACCOUNT, user, bucket));
XmlPath result = deleteObjects(accessKeyId, "s3", bucket, false, entry("shared/a.txt"), entry("private/b.txt"));
assertEquals(List.of("shared/a.txt"), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "private/b.txt");
assertGone(bucket, "shared/a.txt");
assertPresent(bucket, "private/b.txt");
}
@Test
void aBucketPolicyDenyOverridesAnIdentityAllow() {
assertBucketPolicyDenyApplies("s3", "delobj-bp-deny");
}
@Test
void aBucketPolicyDenyAppliesToAnS3ExpressScopedCredential() {
assertBucketPolicyDenyApplies("s3express", "delobj-express");
}
// A lambda-scoped request to this route is answered 404 by AwsRestRouteScopeFilter before the
// handler runs, so ssm, whose scope does reach it, stands in for a credential scoped to another service.
@Test
void aBucketPolicyDenyAppliesToACredentialScopedToAnotherService() {
assertBucketPolicyDenyApplies("ssm", "delobj-other-scope");
}
// filter() returns before its key checks on DeleteObjects, a route no IAM action maps, so the per-key
// check is where an unusable key is refused. An s3express alias is answered in S3's vocabulary, not
// with the codes other services use.
@Test
void aDeactivatedKeySignedForS3ExpressIsRefusedAsS3RefusesIt() {
String bucket = bucket("delobj-inactive");
put(bucket, "a.txt");
String user = uniqueName("delobj-inactive");
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/*"));
given().formParam("Action", "UpdateAccessKey").formParam("UserName", user)
.formParam("AccessKeyId", accessKeyId).formParam("Status", "Inactive")
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200);
XmlPath result = deleteObjects(accessKeyId, "s3express", bucket, false, entry("a.txt"));
assertEquals(List.of(), result.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("a.txt"), result.getList("DeleteResult.Error.Key"));
assertEquals(List.of("InvalidAccessKeyId"), result.getList("DeleteResult.Error.Code"));
assertPresent(bucket, "a.txt");
}
@Test
void anExpiredSessionSignedForS3ExpressIsRefusedAsS3RefusesIt() {
String bucket = bucket("delobj-expired");
put(bucket, "a.txt");
String accessKeyId = "ASIADELOBJ" + UUID.randomUUID().toString().replace("-", "")
.substring(0, 10).toUpperCase(Locale.ROOT);
iamService.registerSessionForAccount(ACCOUNT, accessKeyId, "secret",
"arn:aws:iam::" + ACCOUNT + ":role/delobj-expired", Instant.parse("2020-01-01T00:00:00Z"), null);
try {
XmlPath result = deleteObjects(accessKeyId, "s3express", bucket, false, entry("a.txt"));
assertEquals(List.of(), result.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("a.txt"), result.getList("DeleteResult.Error.Key"));
assertEquals(List.of("ExpiredToken"), result.getList("DeleteResult.Error.Code"));
assertPresent(bucket, "a.txt");
} finally {
iamService.unregisterSession(ACCOUNT, accessKeyId);
}
}
@Test
void bypassingGovernanceRetentionNeedsTheBypassPermission() {
String bucket = bucket("delobj-governance");
enableVersioning(bucket);
String versionId = putGovernanceRetained(bucket, "retained.txt");
String plainVersionId = put(bucket, "plain.txt");
String user = uniqueName("delobj-governance");
String accessKeyId = createUser(user);
String objects = "arn:aws:s3:::" + bucket + "/*";
// The header asks for the bypass on both entries, but only the retained one needs the permission.
userPolicy(user, allow("s3:DeleteObjectVersion", objects) + "," + deny("s3:BypassGovernanceRetention", objects));
XmlPath denied = deleteObjects(accessKeyId, "s3", bucket, false, true,
versionEntry("retained.txt", versionId), versionEntry("plain.txt", plainVersionId));
assertEquals(List.of("plain.txt"), denied.getList("DeleteResult.Deleted.Key"));
assertDenied(denied, "retained.txt");
assertVersionPresent(bucket, "retained.txt", versionId);
userPolicy(user, allow(List.of("s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"), objects));
// Without the header the retention itself refuses the delete, and that error names the version too.
XmlPath retained = deleteObjects(accessKeyId, "s3", bucket, false, false, versionEntry("retained.txt", versionId));
assertEquals(List.of("retained.txt"), retained.getList("DeleteResult.Error.Key"));
assertEquals(List.of(versionId), retained.getList("DeleteResult.Error.VersionId"));
assertVersionPresent(bucket, "retained.txt", versionId);
XmlPath allowed = deleteObjects(accessKeyId, "s3", bucket, false, true, versionEntry("retained.txt", versionId));
assertEquals(List.of("retained.txt"), allowed.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of(versionId), allowed.getList("DeleteResult.Deleted.VersionId"));
assertEquals(List.of(), allowed.getList("DeleteResult.Error.Key"));
}
// An object written before versioning was enabled is the null version, which an entry names as
// VersionId "null". Its retention protects it as any version's does, so the bypass needs the permission.
@Test
void bypassingGovernanceRetentionOnTheNullVersionNeedsTheBypassPermission() {
String bucket = bucket("delobj-governance-null");
putGovernanceRetained(bucket, "retained.txt");
enableVersioning(bucket);
String user = uniqueName("delobj-governance-null");
String accessKeyId = createUser(user);
String objects = "arn:aws:s3:::" + bucket + "/*";
userPolicy(user, allow("s3:DeleteObjectVersion", objects) + "," + deny("s3:BypassGovernanceRetention", objects));
XmlPath denied = deleteObjects(accessKeyId, "s3", bucket, false, true, versionEntry("retained.txt", "null"));
assertEquals(List.of(), denied.getList("DeleteResult.Deleted.Key"));
assertDenied(denied, "retained.txt");
assertPresent(bucket, "retained.txt");
userPolicy(user, allow(List.of("s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"), objects));
XmlPath allowed = deleteObjects(accessKeyId, "s3", bucket, false, true, versionEntry("retained.txt", "null"));
assertEquals(List.of("retained.txt"), allowed.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("null"), allowed.getList("DeleteResult.Deleted.VersionId"));
assertEquals(List.of(), allowed.getList("DeleteResult.Error.Key"));
assertGone(bucket, "retained.txt");
}
// With no pre-versioning object there is no null version, so the retained current version at the
// plain key does not make a "null" entry need the bypass permission.
@Test
void aNullVersionEntryDoesNotInheritTheRetentionOfAVersionedObject() {
String bucket = bucket("delobj-governance-no-null");
enableVersioning(bucket);
String versionId = putGovernanceRetained(bucket, "retained.txt");
String user = uniqueName("delobj-governance-no-null");
String accessKeyId = createUser(user);
String objects = "arn:aws:s3:::" + bucket + "/*";
userPolicy(user, allow("s3:DeleteObjectVersion", objects) + "," + deny("s3:BypassGovernanceRetention", objects));
XmlPath result = deleteObjects(accessKeyId, "s3", bucket, false, true, versionEntry("retained.txt", "null"));
// S3 answers a delete of a version that does not exist as deleted.
assertEquals(List.of("retained.txt"), result.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of("null"), result.getList("DeleteResult.Deleted.VersionId"));
assertEquals(List.of(), result.getList("DeleteResult.Error.Key"));
assertVersionPresent(bucket, "retained.txt", versionId);
}
@Test
void aPresignedRequestIsAuthorizedPerKey() {
String bucket = bucket("delobj-presigned");
put(bucket, "allowed/a.txt");
put(bucket, "protected/b.txt");
String user = uniqueName("delobj-presigned");
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/allowed/*"));
XmlPath result = presignedDeleteObjects(given(), bucket, accessKeyId,
entry("allowed/a.txt"), entry("protected/b.txt"));
assertEquals(List.of("allowed/a.txt"), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "protected/b.txt");
assertGone(bucket, "allowed/a.txt");
assertPresent(bucket, "protected/b.txt");
}
// The filter treats an empty Authorization header as absent and evaluates the query credential,
// so the per-key checks must read the same credential rather than the empty header.
@Test
void aPresignedRequestWithAnEmptyAuthorizationHeaderIsStillAuthorizedPerKey() {
String bucket = bucket("delobj-presigned-empty");
put(bucket, "allowed/a.txt");
put(bucket, "protected/b.txt");
String user = uniqueName("delobj-presigned-empty");
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/allowed/*"));
XmlPath result = presignedDeleteObjects(given().header("Authorization", ""), bucket, accessKeyId,
entry("allowed/a.txt"), entry("protected/b.txt"));
assertEquals(List.of("allowed/a.txt"), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "protected/b.txt");
assertGone(bucket, "allowed/a.txt");
assertPresent(bucket, "protected/b.txt");
}
private void assertBucketPolicyDenyApplies(String signingScope, String prefix) {
String bucket = bucket(prefix);
put(bucket, "open/a.txt");
put(bucket, "protected/b.txt");
String user = uniqueName(prefix);
String accessKeyId = createUser(user);
userPolicy(user, allow("s3:DeleteObject", "arn:aws:s3:::" + bucket + "/*"));
bucketPolicy(bucket, """
{"Effect":"Deny","Principal":"*","Action":"s3:DeleteObject",
"Resource":"arn:aws:s3:::%s/protected/*"}""".formatted(bucket));
XmlPath result = deleteObjects(accessKeyId, signingScope, bucket, false,
entry("open/a.txt"), entry("protected/b.txt"));
assertEquals(List.of("open/a.txt"), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "protected/b.txt");
assertGone(bucket, "open/a.txt");
assertPresent(bucket, "protected/b.txt");
}
private static void assertDenied(XmlPath result, String key) {
assertEquals(List.of(key), result.getList("DeleteResult.Error.Key"));
assertEquals(List.of("AccessDenied"), result.getList("DeleteResult.Error.Code"));
assertEquals(List.of("Access Denied"), result.getList("DeleteResult.Error.Message"));
}
private static XmlPath deleteObjects(String accessKeyId, String signingScope, String bucket, boolean quiet,
String... entries) {
return deleteObjects(accessKeyId, signingScope, bucket, quiet, false, entries);
}
private static XmlPath deleteObjects(String accessKeyId, String signingScope, String bucket, boolean quiet,
boolean bypassGovernanceRetention, String... entries) {
RequestSpecification request = given().header("Authorization", auth(accessKeyId, signingScope));
if (bypassGovernanceRetention) {
request.header("x-amz-bypass-governance-retention", "true");
}
String response = request
.contentType("application/xml")
.body(deleteBody(quiet, entries))
.when()
.post("/" + bucket + "?delete")
.then()
.statusCode(200)
.extract().asString();
return XmlPath.from(response);
}
private static XmlPath presignedDeleteObjects(RequestSpecification request, String bucket, String accessKeyId,
String... entries) {
String response = request
.urlEncodingEnabled(false)
.contentType("application/xml")
.body(deleteBody(false, entries))
.when()
.post(presignedDeletePath(bucket, accessKeyId))
.then()
.statusCode(200)
.extract().asString();
return XmlPath.from(response);
}
private static String deleteBody(boolean quiet, String... entries) {
return "<Delete>" + (quiet ? "<Quiet>true</Quiet>" : "") + String.join("", entries) + "</Delete>";
}
private static String entry(String key) {
return "<Object><Key>" + key + "</Key></Object>";
}
private static String versionEntry(String key, String versionId) {
return "<Object><Key>" + key + "</Key><VersionId>" + versionId + "</VersionId></Object>";
}
private static String eTagEntry(String key, String eTag) {
return "<Object><Key>" + key + "</Key><ETag>" + eTag + "</ETag></Object>";
}
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";
}
private static String bucket(String prefix) {
String bucket = uniqueName(prefix);
given().header("Authorization", auth(ADMIN, "s3")).when().put("/" + bucket).then().statusCode(200);
return bucket;
}
private static String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
private static String put(String bucket, String key) {
return given().header("Authorization", auth(ADMIN, "s3")).body("seed")
.when().put("/" + bucket + "/" + key).then().statusCode(200)
.extract().header("x-amz-version-id");
}
private static String putGovernanceRetained(String bucket, String key) {
return given().header("Authorization", auth(ADMIN, "s3"))
.header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2099-01-01T00:00:00Z")
.body("seed")
.when().put("/" + bucket + "/" + key).then().statusCode(200)
.extract().header("x-amz-version-id");
}
private static void enableVersioning(String bucket) {
given().header("Authorization", auth(ADMIN, "s3")).contentType("application/xml")
.body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
.when().put("/" + bucket + "?versioning").then().statusCode(200);
}
private static void assertPresent(String bucket, String key) {
given().header("Authorization", auth(ADMIN, "s3")).when().head("/" + bucket + "/" + key)
.then().statusCode(200);
}
private static void assertGone(String bucket, String key) {
given().header("Authorization", auth(ADMIN, "s3")).when().head("/" + bucket + "/" + key)
.then().statusCode(404);
}
private static void assertVersionPresent(String bucket, String key, String versionId) {
given().header("Authorization", auth(ADMIN, "s3")).when()
.head("/" + bucket + "/" + key + "?versionId=" + versionId).then().statusCode(200);
}
private String createUser(String user) {
return EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"), user).accessKeyId();
}
private static String allow(String action, String resource) {
return allow(List.of(action), resource);
}
private static String allow(List<String> actions, String resource) {
String actionList = String.join("\",\"", actions);
return "{\"Effect\":\"Allow\",\"Action\":[\"" + actionList + "\"],\"Resource\":\"" + resource + "\"}";
}
private static String deny(String action, String resource) {
return "{\"Effect\":\"Deny\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
}
private static void userPolicy(String user, String statement) {
given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statement + "]}")
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200);
}
private static void bucketPolicy(String bucket, String statement) {
given().header("Authorization", auth(ADMIN, "s3")).contentType("application/json")
.body("{\"Version\":\"2012-10-17\",\"Statement\":[" + statement + "]}")
.when().put("/" + bucket + "?policy").then().statusCode(200);
}
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.xml.XmlPath;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The per-key DeleteObjects authorization of {@link S3DeleteObjectsIamEnforcementIntegrationTest}
* with S3 auth enforcement and the global bucket namespace on as well, so S3's own signed
* bucket-policy check runs beside IAM's. That check evaluates a narrower condition context than
* the IAM layer, so a batch delete must reach the IAM evaluation to be refused exactly where the
* single-key DeleteObject is.
*/
@QuarkusTest
@TestProfile(S3IamEnforcementProfile.class)
class S3DeleteObjectsSignedIamEnforcementIntegrationTest {
// S3HeaderSignatureFilter verifies every header signature under this profile, so each S3 call
// signs for real with the caller's secret.
private static final S3RequestSigner ROOT_SIGNER = S3RequestSigner.signedAs("test", "test");
private static final String REGION = "us-east-1";
private static final String ACCOUNT_A = "111122223333";
private static final String ACCOUNT_B = "222233334444";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void aBucketPolicyDenyOnRequestedRegionAppliesAsItDoesToASingleDelete() {
String bucket = uniqueName("delobj-region");
createBucket(bucket, ROOT_SIGNER);
put(bucket, "single.txt", ROOT_SIGNER);
put(bucket, "batch.txt", ROOT_SIGNER);
String user = uniqueName("delobj-region");
UserCredentials caller = createUser(user, "test");
userPolicy(user, "test",
"{\"Effect\":\"Allow\",\"Action\":\"s3:DeleteObject\",\"Resource\":\"arn:aws:s3:::" + bucket + "/*\"}");
bucketPolicy(bucket, ROOT_SIGNER, """
{"Effect":"Deny","Principal":"*","Action":"s3:DeleteObject","Resource":"arn:aws:s3:::%s/*",
"Condition":{"StringEquals":{"aws:RequestedRegion":"%s"}}}""".formatted(bucket, REGION));
given().filter(signer(caller)).when().delete("/" + bucket + "/single.txt").then().statusCode(403);
XmlPath result = deleteObjects(signer(caller), bucket, "batch.txt");
assertEquals(List.of(), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "batch.txt");
assertPresent(bucket, "single.txt", ROOT_SIGNER);
assertPresent(bucket, "batch.txt", ROOT_SIGNER);
}
// Only the denial is asserted: S3Service.deleteObject looks the bucket up in the caller's own
// account, so a cross-account object delete answers NoSuchBucket here, single-key or batch.
@Test
void aCrossAccountBucketPolicyGrantWithoutAnIdentityGrantIsDenied() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "delobj-cross-" + suffix;
String owner = "delobj-owner-" + suffix;
UserCredentials ownerCredentials = createUser(owner, ACCOUNT_A);
userPolicy(owner, ACCOUNT_A, "{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}");
createBucket(bucket, signer(ownerCredentials));
put(bucket, "shared.txt", signer(ownerCredentials));
String user = "delobj-cross-user-" + suffix;
UserCredentials caller = createUser(user, ACCOUNT_B);
bucketPolicy(bucket, signer(ownerCredentials), """
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:user/%s"},
"Action":"s3:DeleteObject","Resource":"arn:aws:s3:::%s/*"}""".formatted(ACCOUNT_B, user, bucket));
XmlPath result = deleteObjects(signer(caller), bucket, "shared.txt");
assertEquals(List.of(), result.getList("DeleteResult.Deleted.Key"));
assertDenied(result, "shared.txt");
assertPresent(bucket, "shared.txt", signer(ownerCredentials));
}
// The IAM layer skips an access key it does not know, as it skips an unsigned request, so with S3
// auth enforcement on it is S3's own request authentication that refuses the batch outright.
@Test
void anAccessKeyNoOneIssuedIsRefusedBeforeAnyKeyIsDeleted() {
String bucket = uniqueName("delobj-unknown-key");
createBucket(bucket, ROOT_SIGNER);
put(bucket, "kept.txt", ROOT_SIGNER);
S3RequestSigner unknown = S3RequestSigner.signedAs("AKIAUNKNOWNDELOBJ001", "not-a-real-secret");
given()
.filter(unknown)
.contentType("application/xml")
.body("<Delete><Object><Key>kept.txt</Key></Object></Delete>")
.when()
.post("/" + bucket + "?delete")
.then()
.statusCode(403)
.body("Error.Code", equalTo("InvalidAccessKeyId"));
assertPresent(bucket, "kept.txt", ROOT_SIGNER);
}
private static void assertDenied(XmlPath result, String key) {
assertEquals(List.of(key), result.getList("DeleteResult.Error.Key"));
assertEquals(List.of("AccessDenied"), result.getList("DeleteResult.Error.Code"));
assertEquals(List.of("Access Denied"), result.getList("DeleteResult.Error.Message"));
}
private static XmlPath deleteObjects(S3RequestSigner signer, String bucket, String key) {
String response = given()
.filter(signer)
.contentType("application/xml")
.body("<Delete><Object><Key>" + key + "</Key></Object></Delete>")
.when()
.post("/" + bucket + "?delete")
.then()
.statusCode(200)
.extract().asString();
return XmlPath.from(response);
}
private static String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
private static void createBucket(String bucket, S3RequestSigner signer) {
given().filter(signer).when().put("/" + bucket).then().statusCode(200);
}
private static void put(String bucket, String key, S3RequestSigner signer) {
given().filter(signer).contentType("text/plain").body("seed")
.when().put("/" + bucket + "/" + key).then().statusCode(200);
}
private static void assertPresent(String bucket, String key, S3RequestSigner signer) {
given().filter(signer).when().head("/" + bucket + "/" + key).then().statusCode(200);
}
private static void bucketPolicy(String bucket, S3RequestSigner signer, String statement) {
given().filter(signer).contentType("application/json")
.body("{\"Version\":\"2012-10-17\",\"Statement\":[" + statement + "]}")
.when().put("/" + bucket + "?policy").then().statusCode(200);
}
private UserCredentials createUser(String user, String accountKey) {
return EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(accountKey, "iam"), user);
}
private static S3RequestSigner signer(UserCredentials credentials) {
return S3RequestSigner.signedAs(credentials.accessKeyId(), credentials.secretAccessKey());
}
private static void userPolicy(String user, String accountKey, String statement) {
given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statement + "]}")
.header("Authorization", auth(accountKey, "iam")).when().post("/").then().statusCode(200);
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.testing;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
@@ -7,7 +8,8 @@ import static io.restassured.RestAssured.given;
/**
* Takes an IAM user or an S3 bucket that an enforcement test created back out of the shared
* application. A {@code @QuarkusTest} shares one application with every other test class, so a
* application, and makes the users such a test signs as ({@link #createUser}, {@link #auth}),
* registering each one's removal as it goes. A {@code @QuarkusTest} shares one application with every other test class, so a
* fixture left behind outlives the class that made it and is visible to the next class that lists
* users or buckets unscoped. Registered with {@link PartitionCleanup} as each fixture is made.
*
@@ -72,6 +74,39 @@ public final class EnforcementFixtures {
iam(port, authorization, "DeleteUser", "UserName", userName).statusCode(200);
}
/** The access key {@link #createUser} issued, with the secret a request signer needs. */
public record UserCredentials(String accessKeyId, String secretAccessKey) {
}
/**
* Creates an IAM user holding one access key, registering its {@link #removeUser} with
* {@code cleanup} before the create runs, so the user and its key go after the test whatever
* the test does with them.
*
* @param authorization an IAM-scoped header for the account the user belongs to, as for
* {@link #removeUser}, which is handed the same one
*/
public static UserCredentials createUser(PartitionCleanup cleanup, int port, String authorization,
String userName) {
cleanup.register(() -> removeUser(port, authorization, userName));
iam(port, authorization, "CreateUser", "UserName", userName).statusCode(200);
XmlPath key = iam(port, authorization, "CreateAccessKey", "UserName", userName)
.statusCode(200).extract().xmlPath();
return new UserCredentials(
key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"),
key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));
}
/**
* A SigV4 {@code Authorization} header naming {@code accessKeyId}, scoped to {@code service} in
* {@code us-east-1}. The signature is a placeholder, so under a profile that verifies signatures
* the request has to be signed for real instead.
*/
public static String auth(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260629/us-east-1/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
/**
* Deletes an S3 bucket, and first whatever it still holds: "All objects (including all object
* versions and delete markers) in the bucket must be deleted before the bucket itself can be