fix(s3): preserve bucket ownership across account routing (#6117)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-22 12:33:06 -04:00
1 parent d7c139cb69
commit 88be39a7d4
33 files changed
+1209 -57

No files matched your search

@@ -1,7 +1,9 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.s3.S3Controller;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -15,11 +17,13 @@ import org.mockito.ArgumentCaptor;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -36,6 +40,8 @@ class AccountContextFilterTest {
private Map<String, String> sessionAccounts;
private boolean allowUnknownRegions;
private boolean strictPartitions;
private boolean enforceIam;
private ResolvedServiceCatalog catalog;
private AccountContextFilter filter;
@BeforeEach
@@ -46,9 +52,37 @@ class AccountContextFilterTest {
sessionAccounts = new java.util.HashMap<>();
allowUnknownRegions = false;
strictPartitions = false;
enforceIam = false;
catalog = mock(ResolvedServiceCatalog.class);
when(catalog.byResourceClass(S3Controller.class)).thenReturn(Optional.of(legacyDescriptor()));
SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup,
this::config);
this::config, () -> catalog);
}
private ServiceDescriptor legacyDescriptor() {
return new ServiceDescriptor("s3", "s3", true, true, "s3", "memory", 0L,
null, ServiceProtocol.REST_XML, Set.of(ServiceProtocol.REST_XML), Set.of(),
Set.of("s3"), Set.of(), Set.of(S3Controller.class), Set.of(), true);
}
@Test
void legacyAdmissionComesFromTheRegisteredService() {
filter.resourceInfo = mock(ResourceInfo.class);
doReturn(AccountContextFilterTest.class).when(filter.resourceInfo).getResourceClass();
when(catalog.byResourceClass(AccountContextFilterTest.class))
.thenReturn(Optional.of(legacyDescriptor()));
filter.filter(mockContext("AWS 000000000001:signature", null));
assertEquals("000000000001", requestContext.getAccountId());
}
@Test
void anUnregisteredResourceDoesNotAdmitLegacyAuthorization() {
filter.resourceInfo = mock(ResourceInfo.class);
doReturn(S3Controller.class).when(filter.resourceInfo).getResourceClass();
when(catalog.byResourceClass(S3Controller.class)).thenReturn(Optional.empty());
filter.filter(mockContext("AWS 000000000001:signature", null));
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
}
private EmulatorConfig config() {
@@ -57,9 +91,59 @@ class AccountContextFilterTest {
when(partitions.strict()).thenReturn(strictPartitions);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.partitions()).thenReturn(partitions);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.iam()).thenReturn(iam);
when(iam.enforcementEnabled()).thenReturn(enforceIam);
return config;
}
@ParameterizedTest
@ValueSource(strings = {"000000000001", "AKIAEXAMPLE", "ASIAEXAMPLE"})
void permissiveS3LegacyHeadersUseTheCredentialAccount(String accessKeyId) {
sessionAccounts.put(accessKeyId, "000000000001");
filter.resourceInfo = mock(ResourceInfo.class);
doReturn(S3Controller.class).when(filter.resourceInfo).getResourceClass();
filter.filter(mockContext("AWS " + accessKeyId + ":signature", null));
assertEquals("000000000001", requestContext.getAccountId());
assertEquals(accessKeyId, requestContext.getAccessKeyId());
assertEquals(DEFAULT_REGION, requestContext.getRegion());
}
@Test
void legacyHeadersLeaveOtherResourcesAndIamEnforcementUnchanged() {
filter.resourceInfo = mock(ResourceInfo.class);
doReturn(AccountContextFilterTest.class).when(filter.resourceInfo).getResourceClass();
filter.filter(mockContext("AWS 000000000001:signature", null));
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertNull(requestContext.getAccessKeyId());
doReturn(S3Controller.class).when(filter.resourceInfo).getResourceClass();
enforceIam = true;
filter.filter(mockContext("AWS 000000000001:signature", null));
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertNull(requestContext.getAccessKeyId());
}
@Test
void modernS3HeadersRetainTheirRegionAndUnknownLegacyKeysUseTheDefault() {
filter.resourceInfo = mock(ResourceInfo.class);
doReturn(S3Controller.class).when(filter.resourceInfo).getResourceClass();
filter.filter(mockContext("AWS4-HMAC-SHA256 Credential=000000000001/20260617/us-west-2/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc", null));
assertEquals("000000000001", requestContext.getAccountId());
assertEquals("us-west-2", requestContext.getRegion());
filter.filter(mockContext("AWS unknown-key:signature", null));
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertEquals(DEFAULT_REGION, requestContext.getRegion());
assertEquals("unknown-key", requestContext.getAccessKeyId());
filter.filter(mockContext(null, null));
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertNull(requestContext.getAccessKeyId());
}
@Test
void resolvesFromAuthHeaderWhenPresent() {
ContainerRequestContext ctx = mockContext(
@@ -133,7 +217,7 @@ class AccountContextFilterTest {
void anUnsignedRequestGetsTheDeploymentPartition() {
RegionResolver china = new RegionResolver("cn-north-1", DEFAULT_ACCOUNT);
AccountContextFilter chinaFilter = new AccountContextFilter(accountResolver, china, requestContext,
akid -> Optional.empty(), this::config);
akid -> Optional.empty(), this::config, () -> catalog);
chinaFilter.filter(mockContext(null, null));
assertEquals("cn-north-1", requestContext.getRegion());
assertEquals("aws-cn", requestContext.getPartition());
@@ -523,7 +607,7 @@ class AccountContextFilterTest {
strictPartitions = true;
RegionResolver gov = new RegionResolver("us-gov-west-1", DEFAULT_ACCOUNT);
AccountContextFilter govFilter = new AccountContextFilter(accountResolver, gov, requestContext,
key -> Optional.empty(), this::config);
key -> Optional.empty(), this::config, () -> catalog);
String credential = "AKID/20261015/custom:222222222222/cloudfront/aws4_request";
ContainerRequestContext ctx = mockContext(query ? null : "AWS4-HMAC-SHA256 Credential=" + credential,
query ? credential : null);
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -60,6 +62,30 @@ class AccountResolverTest {
assertEquals("000000000001", resolver.resolve(auth));
}
@ParameterizedTest
@ValueSource(strings = {"000000000001", "AKIAEXAMPLE", "ASIAEXAMPLE"})
void legacyS3ExtractionDoesNotChangeSharedAuthenticationParsing(String accessKeyId) {
String header = "AWS " + accessKeyId + ":signature=";
assertEquals(accessKeyId, resolver.extractS3AccessKeyId(header));
assertNull(resolver.extractAccessKeyId(header));
assertEquals(DEFAULT_ACCOUNT, resolver.resolve(header));
}
@ParameterizedTest
@ValueSource(strings = {"", "AWS key:", "AWS :signature", "AWS key:signature extra",
"AWS key:signature:extra", "AWS key :signature", "Basic key:signature", "aws key:signature"})
void malformedLegacyHeadersDoNotSelectAnAccount(String header) {
assertNull(resolver.extractS3AccessKeyId(header));
}
@Test
void legacyS3ExtractionRetainsModernAndAbsentHeaders() {
String header = "AWS4-HMAC-SHA256 Credential=ASIAEXAMPLE/20260617/us-west-2/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
assertEquals("ASIAEXAMPLE", resolver.extractS3AccessKeyId(header));
assertNull(resolver.extractS3AccessKeyId(null));
}
// --- resolveFromPresignedCredential(String credentialValue) tests ---
@Test
@@ -57,6 +57,14 @@ class SigV4HeaderSignatureIntegrationTest {
private static String userAccessKeyId;
private static String userSecretKey;
@Test
@Order(100)
void legacyS3HeadersRemainRejectedWhenGlobalSignatureValidationIsEnabled() {
given().header("Authorization", "AWS 000000000001:local-signature")
.put("/legacy-signature-rejected")
.then().statusCode(400).body(containsString("AuthorizationHeaderMalformed"));
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.cur;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ParquetEmitterStagingTest {
@Test
void emissionKeepsItsStagingNameAndUsesInternalCreation() {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
FocusRowProjector projector = mock(FocusRowProjector.class);
when(projector.project(List.of())).thenReturn(List.of());
ParquetEmitter emitter = new ParquetEmitter(projector, duck, s3, new ObjectMapper(),
"floci-cur-staging", "us-east-2");
ParquetEmitter.Result result = emitter.emit("report", "results", "billing", List.of(), "000000000002");
verify(s3).createInternalBucket("floci-cur-staging", "us-east-2");
verify(s3, never()).createBucket("floci-cur-staging", "us-east-2");
verify(s3).putObject(eq("floci-cur-staging"), anyString(), any(byte[].class),
eq("application/x-ndjson"), any());
assertEquals("s3://results/" + result.key(), result.s3Uri());
verify(duck).execute(eq("SELECT 1 AS ok"), anyString(), anyString(), eq("000000000002"));
}
@Test
void aForeignNamespaceConflictIsNotIgnoredBeforeWriting() {
S3Service s3 = mock(S3Service.class);
when(s3.createInternalBucket("floci-cur-staging", "us-east-2"))
.thenThrow(new AwsException("BucketAlreadyExists", "foreign", 409));
ParquetEmitter emitter = new ParquetEmitter(mock(FocusRowProjector.class), mock(FlociDuckClient.class),
s3, new ObjectMapper(), "floci-cur-staging", "us-east-2");
assertEquals("BucketAlreadyExists", assertThrows(AwsException.class,
() -> emitter.emit("report", "results", null, List.of())).getErrorCode());
verify(s3, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
}
}
@@ -169,6 +169,8 @@ class FirehoseParquetConverterTest {
record("{\"ticker\": \"MISSING_FIELDS\"}")), DELIVERY_TIME);
assertEquals(2, outcome.convertedRecords());
verify(s3Service).createInternalBucket(STAGING, "us-east-1");
verify(s3Service, never()).createBucket(STAGING, "us-east-1");
assertEquals(0, outcome.failedRecords());
assertTrue(outcome.dataKey().startsWith("data/2026/01/01/00/stream-1-2026-01-01-00-00-00-"));
assertTrue(outcome.dataKey().endsWith(".parquet"));
@@ -298,7 +298,7 @@ class FirehoseServiceTest {
firehoseService.flush("000000000000", "eu-west-1", "eu-default");
verify(s3Service).createBucket("floci-firehose-results", "us-east-1");
verify(s3Service).createInternalBucket("floci-firehose-results", "us-east-1");
}
@Test
@@ -18,7 +18,7 @@ class EventSourceMappingSerializationTest {
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
controller = new LambdaController(null, null, objectMapper);
controller = new LambdaController(null, null, objectMapper, null);
}
@Test
@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.lambda.zip.DeploymentPackage;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class LambdaTasksBucketTest {
@Test
void deploymentCopiesKeepTheExistingTasksBucketAndObjectKey() {
S3Service s3 = mock(S3Service.class);
byte[] archive = {1, 2, 3};
assertTrue(LambdaService.putTasksObjectQuietly(s3, "us-east-2", "function/code.zip",
DeploymentPackage.of(archive), "test package"));
verify(s3).createInternalBucket("awslambda-us-east-2-tasks", "us-east-2");
verify(s3, never()).createBucket("awslambda-us-east-2-tasks", "us-east-2");
verify(s3).putObject("awslambda-us-east-2-tasks", "function/code.zip", archive,
"application/zip", Map.of());
}
@Test
void anExistingOwnedTasksBucketIsReused() {
S3Service s3 = mock(S3Service.class);
when(s3.createInternalBucket("awslambda-us-east-1-tasks", "us-east-1"))
.thenThrow(new AwsException("BucketAlreadyOwnedByYou", "owned", 409));
assertTrue(LambdaService.putTasksObjectQuietly(s3, "us-east-1", "layer.zip",
DeploymentPackage.of(new byte[]{1}), "test layer"));
}
@Test
void unexpectedStagingFailuresStillRejectTheStoredCopy() {
S3Service s3 = mock(S3Service.class);
when(s3.createInternalBucket("awslambda-us-east-2-tasks", "us-east-2"))
.thenThrow(new AwsException("AccessDenied", "denied", 403));
assertFalse(LambdaService.putTasksObjectQuietly(s3, "us-east-2", "function.zip",
DeploymentPackage.of(new byte[]{1}), "test package"));
}
}
@@ -616,7 +616,7 @@ class ExternalTableMaterializerTest {
@Test
void refusesToUseAScratchBucketNameThatBelongsToAUserBucket() {
when(s3.createBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
when(s3.createInternalBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
.thenThrow(new AwsException("BucketAlreadyOwnedByYou", "owned", 409));
when(s3.getBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET)).thenReturn(Map.of());
when(glue.getTable("lake", "events")).thenReturn(csvTable());
@@ -626,6 +626,7 @@ class ExternalTableMaterializerTest {
assertThat(exception.getMessage(), containsString("not the Spectrum scratch bucket"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
verify(s3, never()).putBucketTagging(eq(ExternalTableMaterializer.SCRATCH_BUCKET), any());
verify(s3, never()).deleteObject(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString());
}
@@ -636,7 +637,7 @@ class ExternalTableMaterializerTest {
verify(s3).putBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET, Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
when(s3.createBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
when(s3.createInternalBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
.thenThrow(new AwsException("BucketAlreadyOwnedByYou", "owned", 409));
when(s3.getBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET)).thenReturn(Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
@@ -76,6 +76,14 @@ class S3AuthEnforcementIntegrationTest {
private static final S3RequestSigner BAD_KEY_SIGNER = S3RequestSigner.signedAs("bad-key", "bad-secret");
private static final S3RequestSigner ACCOUNT_SHAPED_SIGNER = S3RequestSigner.signedAs("123456789012", "test");
@Test
@Order(60)
void legacyHeadersRemainRejectedWhenS3AuthenticationIsEnforced() {
given().header("Authorization", "AWS 000000000001:local-signature")
.put("/legacy-auth-rejected")
.then().statusCode(400).body(containsString("AuthorizationHeaderMalformed"));
}
private static void enableLegacyAcls(String bucket) {
given().filter(LOCAL_SIGNER)
.body("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>")
@@ -0,0 +1,179 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class S3BucketCreationAccountTest {
private static final String ACCOUNT_A = "000000000001";
private static final String ACCOUNT_B = "000000000002";
private final ThreadLocal<String> caller = ThreadLocal.withInitial(() -> ACCOUNT_A);
private AccountAwareStorageBackend<Bucket> buckets;
private AccountAwareStorageBackend<S3Object> objects;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
RequestContext request = mock(RequestContext.class);
when(request.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> context = mock(Instance.class);
when(context.get()).thenReturn(request);
buckets = spy(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, ACCOUNT_A));
objects = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, ACCOUNT_A);
}
private S3Service service(boolean global) {
return new S3Service(buckets, objects, Path.of("s3-account-create-test"), true, global);
}
@Test
void globalNamespaceRejectsForeignNamesWithoutCreatingAShadowBucket() {
S3Service service = service(true);
Bucket owner = service.createBucket("unique-bucket", "us-east-2");
caller.set(ACCOUNT_B);
AwsException rejected = assertThrows(AwsException.class,
() -> service.createBucket("unique-bucket", "us-east-1"));
assertEquals("BucketAlreadyExists", rejected.getErrorCode());
assertEquals(409, rejected.getHttpStatus());
assertEquals("The requested bucket name is not available. The bucket namespace is shared by all users "
+ "of the system. Please select a different name and try again.", rejected.getMessage());
assertTrue(service.listBuckets().isEmpty());
assertTrue(buckets.getForAccount(ACCOUNT_B, "unique-bucket").isEmpty());
assertSame(owner, buckets.getForAccount(ACCOUNT_A, "unique-bucket").orElseThrow());
}
@ParameterizedTest
@ValueSource(strings = {"awslambda-us-east-1-tasks", "floci-internal-redshift-spectrum-scratch",
"floci-firehose-staging", "floci-firehose-results", "floci-cur-staging"})
void internalBucketsKeepTheirNamesAndObjectsInEachAccount(String name) {
S3Service service = service(true);
service.createInternalBucket(name, "us-east-1");
service.putObject(name, "function.zip", "owner".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
caller.set(ACCOUNT_B);
assertEquals("BucketAlreadyExists", assertThrows(AwsException.class,
() -> service.createBucket(name, "us-east-1")).getErrorCode());
service.createInternalBucket(name, "us-east-1");
service.putObject(name, "function.zip", "second".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
assertEquals(name, buckets.getForAccount(ACCOUNT_A, name).orElseThrow().getName());
assertEquals(name, buckets.getForAccount(ACCOUNT_B, name).orElseThrow().getName());
assertTrue(objects.getForAccount(ACCOUNT_A, name + "/function.zip").isPresent());
assertArrayEquals("second".getBytes(StandardCharsets.UTF_8),
service.getObject(name, "function.zip").getData());
caller.set(ACCOUNT_A);
assertArrayEquals("owner".getBytes(StandardCharsets.UTF_8),
service.getObject(name, "function.zip").getData());
}
@Test
void internalCreationReportsExistingUserBucketsEvenInTheDefaultRegion() {
S3Service service = service(true);
Bucket userBucket = service.createBucket("floci-redshift-spectrum", "us-east-1");
assertEquals("BucketAlreadyOwnedByYou", assertThrows(AwsException.class,
() -> service.createInternalBucket("floci-redshift-spectrum", "us-east-1")).getErrorCode());
assertSame(userBucket, buckets.getForAccount(ACCOUNT_A, "floci-redshift-spectrum").orElseThrow());
assertTrue(service.getBucketTagging("floci-redshift-spectrum").isEmpty());
}
@Test
void defaultNamespaceStillAllowsTheSameNameInDifferentAccounts() {
S3Service service = service(false);
service.createBucket("isolated-bucket", "us-east-2");
caller.set(ACCOUNT_B);
service.createBucket("isolated-bucket", "us-east-2");
assertTrue(buckets.getForAccount(ACCOUNT_A, "isolated-bucket").isPresent());
assertTrue(buckets.getForAccount(ACCOUNT_B, "isolated-bucket").isPresent());
}
@Test
void sameOwnerRetainsTheDefaultRegionExceptionAndOtherRegionConflict() {
S3Service service = service(true);
Bucket east = service.createBucket("default-region-bucket", "us-east-1");
assertSame(east, service.createBucket("default-region-bucket", "us-east-1"));
Bucket regional = service.createBucket("regional-bucket", "us-east-2");
AwsException rejected = assertThrows(AwsException.class,
() -> service.createBucket("regional-bucket", "us-east-2"));
assertEquals("BucketAlreadyOwnedByYou", rejected.getErrorCode());
assertSame(regional, buckets.getForAccount(ACCOUNT_A, "regional-bucket").orElseThrow());
}
@Test
void deletingTheOwnerBucketAllowsAnotherAccountToCreateTheName() {
S3Service service = service(true);
service.createBucket("reusable-bucket", "us-east-2");
service.deleteBucket("reusable-bucket");
caller.set(ACCOUNT_B);
service.createBucket("reusable-bucket", "us-east-2");
assertTrue(buckets.getForAccount(ACCOUNT_A, "reusable-bucket").isEmpty());
assertTrue(buckets.getForAccount(ACCOUNT_B, "reusable-bucket").isPresent());
}
@Test
void globalCreationKeepsTheCollisionCheckAndPublicationInOneCriticalSection() throws Exception {
S3Service service = service(true);
CountDownLatch publicationEntered = new CountDownLatch(1);
CountDownLatch publish = new CountDownLatch(1);
CountDownLatch contenderStarted = new CountDownLatch(1);
doAnswer(invocation -> {
if (ACCOUNT_A.equals(caller.get())) {
publicationEntered.countDown();
assertTrue(publish.await(5, TimeUnit.SECONDS));
}
return invocation.callRealMethod();
}).when(buckets).put(eq("contended-bucket"), any(Bucket.class));
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<Bucket> first = executor.submit(() -> service.createBucket("contended-bucket", "us-east-2"));
assertTrue(publicationEntered.await(5, TimeUnit.SECONDS));
Future<AwsException> second = executor.submit(() -> {
caller.set(ACCOUNT_B);
contenderStarted.countDown();
return assertThrows(AwsException.class,
() -> service.createBucket("contended-bucket", "us-east-2"));
});
assertTrue(contenderStarted.await(5, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> second.get(100, TimeUnit.MILLISECONDS));
publish.countDown();
assertEquals("contended-bucket", first.get(5, TimeUnit.SECONDS).getName());
assertEquals("BucketAlreadyExists", second.get(5, TimeUnit.SECONDS).getErrorCode());
assertTrue(buckets.getForAccount(ACCOUNT_A, "contended-bucket").isPresent());
assertTrue(buckets.getForAccount(ACCOUNT_B, "contended-bucket").isEmpty());
} finally {
publish.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
}
@@ -1,13 +1,18 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
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.response.ExtractableResponse;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.restassured.RestAssured.given;
@@ -24,6 +29,50 @@ class S3BucketPolicyEnforcementIntegrationTest {
private static final String ACCOUNT_B = "222233334444";
private static final S3RequestSigner ROOT_SIGNER = S3RequestSigner.signedAs("test", "test");
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void crossAccountListingRequiresAndHonorsTheOwnersBucketPolicy() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String ownerName = "list-owner-" + suffix;
String readerName = "list-reader-" + suffix;
cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(ACCOUNT_A, "iam"), ownerName));
Credentials owner = createAccountAdmin(ownerName, ACCOUNT_A);
cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(ACCOUNT_B, "iam"), readerName));
Credentials reader = createAccountAdmin(readerName, ACCOUNT_B);
String bucket = "owner-listing-" + suffix;
cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), owner.signer(), bucket));
createBucketAs(bucket, owner.signer());
try {
given().filter(owner.signer()).body("owned-data").put("/" + bucket + "/object.txt")
.then().statusCode(200);
for (String query : new String[]{"", "?list-type=2"}) {
given().filter(reader.signer()).get("/" + bucket + query)
.then().statusCode(403).body(containsString("AccessDenied"));
}
given().filter(owner.signer()).body("""
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::%s"}]}
""".formatted(reader.userArn(), bucket))
.put("/" + bucket + "?policy").then().statusCode(200);
for (String query : new String[]{"", "?list-type=2"}) {
given().filter(reader.signer()).get("/" + bucket + query)
.then().statusCode(200).body(containsString("<Key>object.txt</Key>"));
}
given().filter(owner.signer()).delete("/" + bucket + "?policy").then().statusCode(204);
given().filter(reader.signer()).get("/" + bucket + "?list-type=2")
.then().statusCode(403).body(containsString("AccessDenied"));
} finally {
given().filter(owner.signer()).delete("/" + bucket + "/object.txt");
given().filter(owner.signer()).delete("/" + bucket);
}
}
record Credentials(String accessKeyId, String secretAccessKey, String userArn) {
S3RequestSigner signer() {
return S3RequestSigner.signedAs(accessKeyId, secretAccessKey);
@@ -68,8 +68,6 @@ class S3DeleteObjectsSignedIamEnforcementIntegrationTest {
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);
@@ -92,6 +90,45 @@ class S3DeleteObjectsSignedIamEnforcementIntegrationTest {
assertPresent(bucket, "shared.txt", signer(ownerCredentials));
}
@Test
void crossAccountDeletesRequireBothGrantsAndMutateOnlyTheBucketOwner() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "delobj-owner-" + suffix;
String owner = "delobj-owner-" + suffix;
UserCredentials ownerCredentials = createUser(owner, ACCOUNT_A);
userPolicy(owner, ACCOUNT_A, "{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}");
S3RequestSigner ownerSigner = signer(ownerCredentials);
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), ownerSigner, bucket));
createBucket(bucket, ownerSigner);
put(bucket, "single.txt", ownerSigner);
put(bucket, "batch.txt", ownerSigner);
put(bucket, "retained.txt", ownerSigner);
String user = "delobj-caller-" + suffix;
UserCredentials caller = createUser(user, ACCOUNT_B);
userPolicy(user, ACCOUNT_B, "{\"Effect\":\"Allow\",\"Action\":\"s3:DeleteObject\",\"Resource\":\"*\"}");
S3RequestSigner callerSigner = signer(caller);
given().filter(callerSigner).delete("/" + bucket + "/single.txt").then().statusCode(403);
assertDenied(deleteObjects(callerSigner, bucket, "batch.txt"), "batch.txt");
assertPresent(bucket, "single.txt", ownerSigner);
assertPresent(bucket, "batch.txt", ownerSigner);
bucketPolicy(bucket, ownerSigner, """
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:user/%s"},
"Action":"s3:DeleteObject","Resource":"arn:aws:s3:::%s/*"}""".formatted(ACCOUNT_B, user, bucket));
given().filter(callerSigner).delete("/" + bucket + "/single.txt").then().statusCode(204);
XmlPath deleted = deleteObjects(callerSigner, bucket, "batch.txt");
assertEquals(List.of("batch.txt"), deleted.getList("DeleteResult.Deleted.Key"));
assertEquals(List.of(), deleted.getList("DeleteResult.Error.Key"));
given().filter(ownerSigner).head("/" + bucket + "/single.txt").then().statusCode(404);
given().filter(ownerSigner).head("/" + bucket + "/batch.txt").then().statusCode(404);
given().filter(callerSigner).delete("/" + bucket + "/single.txt").then().statusCode(204);
given().filter(ownerSigner).delete("/" + bucket + "?policy").then().statusCode(204);
given().filter(callerSigner).delete("/" + bucket + "/retained.txt").then().statusCode(403);
assertPresent(bucket, "retained.txt", ownerSigner);
}
// 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
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
@@ -54,6 +55,78 @@ class S3GlobalBucketNamespaceTest {
return inst;
}
@Test
void legacyGovernanceRetentionIsReadableOnlyByTheDefaultOwnerBeforeMigration() {
Instance<RequestContext> context = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, DEFAULT_ACCT);
StorageBackend<String, S3Object> rawObjects = new InMemoryStorage<>();
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(rawObjects, context, DEFAULT_ACCT);
S3Service service = new S3Service(buckets, objects, Path.of("s3-legacy-retention-test"), true, false);
service.createBucket("legacy-retention-bucket", "us-east-1");
service.putBucketVersioning("legacy-retention-bucket", "Enabled");
service.setBucketObjectLockEnabled("legacy-retention-bucket");
S3Object object = service.putObject("legacy-retention-bucket", "object.txt",
"payload".getBytes(UTF_8), "text/plain", Map.of());
String version = object.getVersionId();
service.putObjectRetention("legacy-retention-bucket", "object.txt", version,
"GOVERNANCE", Instant.parse("2035-01-01T00:00:00Z"), true);
String currentKey = "legacy-retention-bucket/object.txt";
String versionKey = currentKey + "#v#" + version;
for (String key : List.of(currentKey, versionKey)) {
rawObjects.put(key, objects.getForAccount(DEFAULT_ACCT, key).orElseThrow());
rawObjects.delete(DEFAULT_ACCT + "/" + key);
}
assertTrue(service.isGovernanceRetentionActive("legacy-retention-bucket", "object.txt", version));
assertTrue(service.deleteOverridesGovernanceRetention("legacy-retention-bucket", "object.txt", version));
assertTrue(rawObjects.get(versionKey).isPresent());
assertTrue(objects.getForAccount(DEFAULT_ACCT, versionKey).isEmpty());
caller.set(ACCOUNT_A);
service.createBucket("legacy-retention-bucket", "us-east-1");
assertFalse(service.isGovernanceRetentionActive("legacy-retention-bucket", "object.txt", version));
assertTrue(objects.getForAccount(ACCOUNT_A, versionKey).isEmpty());
assertTrue(rawObjects.get(versionKey).isPresent());
caller.set(DEFAULT_ACCT);
service.deleteObject("legacy-retention-bucket", "object.txt", version, true);
assertTrue(objects.getForAccount(DEFAULT_ACCT, versionKey).isEmpty());
assertTrue(rawObjects.get(versionKey).isEmpty());
}
@Test
void crossAccountListingsReadTheOwnersObjectsAndPreservePrefixPagination() {
Instance<RequestContext> context = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, DEFAULT_ACCT);
S3Service service = new S3Service(buckets, objects, Path.of("s3-gns-listing-test"), true, true);
caller.set(ACCOUNT_A);
service.createBucket("owner-listing-bucket", "us-east-1");
service.putObject("owner-listing-bucket", "one.txt", "one".getBytes(UTF_8), "text/plain", Map.of());
service.putObject("owner-listing-bucket", "nested/two.txt", "two".getBytes(UTF_8),
"text/plain", Map.of());
caller.set(ACCOUNT_B);
service.putObject("owner-listing-bucket", "three.txt", "three".getBytes(UTF_8), "text/plain", Map.of());
assertEquals(List.of("nested/two.txt", "one.txt", "three.txt"),
service.listObjects("owner-listing-bucket", null, null, 100).stream()
.map(S3Object::getKey).toList());
S3Service.ListObjectsResult first =
service.listObjectsWithPrefixes("owner-listing-bucket", null, "/", 1, null, null);
assertEquals(List.of("nested/"), first.commonPrefixes());
assertTrue(first.isTruncated());
S3Service.ListObjectsResult next =
service.listObjectsWithPrefixes("owner-listing-bucket", null, "/", 100,
first.nextContinuationToken(), null);
assertEquals(List.of("one.txt", "three.txt"), next.objects().stream().map(S3Object::getKey).toList());
assertEquals(List.of("nested/two.txt"),
service.listObjects("owner-listing-bucket", "nested/", null, 100).stream()
.map(S3Object::getKey).toList());
assertTrue(service.listBuckets().isEmpty());
assertTrue(objects.scanForAccount(ACCOUNT_B, key -> true).isEmpty());
}
/**
* CreateBucket only sees the caller's own buckets, so a caller that wants to know whether it
* just created one asks ownsBucket, which stays owner-scoped where bucketExists spans accounts.
@@ -0,0 +1,248 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.firehose.FirehoseLambdaTransformer;
import io.github.hectorvent.floci.services.firehose.FirehoseParquetConverter;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.s3.model.LambdaNotification;
import io.github.hectorvent.floci.services.s3.model.NotificationConfiguration;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import java.net.URI;
import java.nio.file.Path;
import java.time.Clock;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
class S3GlobalLegacyListingTest {
private static final String OWNER = "000000000001";
private static final String CALLER = "000000000002";
private static final String BUCKET = "global-legacy-bucket";
private final RequestContext request = new RequestContext();
private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
private S3Service s3;
private S3Controller controller;
private LambdaService lambda;
private CloudTrailService trail;
private HttpHeaders headers;
private UriInfo uri;
private StorageFactory factory;
private EmulatorConfig config;
private RegionResolver region;
private MockedStatic<RequestScopes> scopes;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
request.setAccountId(OWNER);
request.setRegion("us-east-1");
Instance<RequestContext> context = mock(Instance.class);
when(context.get()).thenReturn(request);
factory = mock(StorageFactory.class);
when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
stores.computeIfAbsent(invocation.getArgument(0) + "/" + invocation.getArgument(1),
key -> new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, OWNER)));
when(factory.create(anyString(), anyString(), any(), any())).thenAnswer(invocation ->
stores.computeIfAbsent(invocation.getArgument(0) + "/" + invocation.getArgument(1),
key -> new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, OWNER)));
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(Path.of("s3-global-legacy-test").toString());
when(config.storage().mode()).thenReturn("memory");
when(config.storage().services().s3().mode()).thenReturn(Optional.empty());
when(config.services().s3().globalBucketNamespace()).thenReturn(true);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
region = new RegionResolver("us-east-1", OWNER);
lambda = mock(LambdaService.class);
Instance<LambdaService> provider = mock(Instance.class);
when(provider.isResolvable()).thenReturn(true);
when(provider.get()).thenReturn(lambda);
s3 = new S3Service(factory, config, null, null, provider, null, null, region, new ObjectMapper(), null);
trail = mock(CloudTrailService.class);
CurrentVertxRequest vertx = mock(CurrentVertxRequest.class, RETURNS_DEEP_STUBS);
when(vertx.getCurrent().request().path()).thenReturn("/" + BUCKET + "/object.txt");
when(vertx.getCurrent().request().getHeader("Authorization")).thenAnswer(invocation ->
"AWS " + request.getAccountId() + ":local-signature");
AccountResolver accounts = mock(AccountResolver.class);
when(accounts.extractS3AccessKeyId(anyString())).thenAnswer(invocation -> request.getAccountId());
controller = new S3Controller(s3, null, region, null, vertx, null, trail, accounts,
request, null, null, config, Clock.systemUTC());
headers = mock(HttpHeaders.class);
uri = mock(UriInfo.class);
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(uri.getRequestUri()).thenReturn(URI.create("http://localhost:4566/" + BUCKET + "/object.txt"));
scopes = mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE));
scopes.when(() -> RequestScopes.callAs(anyString(), any(Supplier.class))).thenAnswer(invocation ->
inAccount(invocation.getArgument(0), invocation.getArgument(1)));
scopes.when(() -> RequestScopes.runAs(anyString(), any(Runnable.class))).thenAnswer(invocation ->
inAccount(invocation.getArgument(0), () -> {
invocation.<Runnable>getArgument(1).run();
return null;
}));
s3.createBucket(BUCKET, "us-east-1");
s3.putObject(BUCKET, "object.txt", "owner-data".getBytes(UTF_8), "text/plain", Map.of());
}
@AfterEach
void tearDown() {
if (scopes != null) {
scopes.close();
}
}
@Test
void crossAccountDeleteKeepsTheFullNotificationArnAndOwnerScope() {
String destination = "arn:aws:lambda:us-east-1:000000000003:function:shared-name:PROD";
NotificationConfiguration notifications = new NotificationConfiguration();
notifications.setLambdaFunctionConfigurations(List.of(
new LambdaNotification("foreign-destination", destination, List.of("s3:ObjectRemoved:*"))));
s3.putBucketNotificationConfiguration(BUCKET, notifications, true);
doAnswer(invocation -> {
assertEquals(OWNER, request.getAccountId());
return null;
}).when(lambda).invoke(anyString(), anyString(), any(byte[].class), eq(InvocationType.Event));
request.setAccountId(CALLER);
assertEquals(204, delete(null).getStatus());
verify(lambda).invoke(eq("us-east-1"), eq(destination), any(byte[].class), eq(InvocationType.Event));
assertEquals(CALLER, request.getAccountId());
assertEquals("NoSuchKey", assertThrows(AwsException.class,
() -> s3.getObject(BUCKET, "object.txt")).getErrorCode());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deletesUseTheOwnerAndRestoreTheLegacyCaller(boolean versioned) {
if (versioned) {
s3.deleteObject(BUCKET, "object.txt", null, false);
s3.putBucketVersioning(BUCKET, "Enabled");
}
String version = s3.putObject(BUCKET, "object.txt", "owner-data".getBytes(UTF_8),
"text/plain", Map.of()).getVersionId();
request.setAccountId(CALLER);
doAnswer(invocation -> {
assertEquals(CALLER, request.getAccountId());
return null;
}).when(trail).emitS3DataEvent(any());
Response removed = delete(null);
assertEquals(204, removed.getStatus());
assertEquals(CALLER, request.getAccountId());
assertEquals("NoSuchKey", assertThrows(AwsException.class,
() -> s3.getObject(BUCKET, "object.txt")).getErrorCode());
if (versioned) {
assertEquals("owner-data", new String(s3.getObject(BUCKET, "object.txt", version).getData(), UTF_8));
assertEquals(204, delete(removed.getHeaderString("x-amz-version-id")).getStatus());
assertEquals("owner-data", new String(s3.getObject(BUCKET, "object.txt").getData(), UTF_8));
assertEquals(204, delete(version).getStatus());
} else {
assertEquals(204, delete(null).getStatus());
}
assertThrows(AwsException.class, () -> s3.deleteBucket(BUCKET));
request.setAccountId(OWNER);
s3.headBucket(BUCKET);
}
@Test
void bothListingVersionsReadTheOwnerAndRecordTheLegacyCaller() {
request.setAccountId(CALLER);
assertEquals("BucketAlreadyExists", assertThrows(AwsException.class,
() -> s3.createBucket(BUCKET, "us-east-1")).getErrorCode());
doAnswer(invocation -> {
CloudTrailService.S3EventInput input = invocation.getArgument(0);
assertEquals(CALLER, request.getAccountId());
assertEquals(CALLER, input.accessKeyId());
return null;
}).when(trail).emitS3DataEvent(any());
for (String listType : new String[]{null, "2"}) {
Response response = controller.listObjects(BUCKET, null, null, null, listType,
null, null, null, null, null, null, uri, headers);
assertEquals(200, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Key>object.txt</Key>"));
assertEquals(CALLER, request.getAccountId());
}
}
@Test
void defaultFirehoseDeliveriesStayInEachStreamsAccount() {
when(config.services().firehose().enabled()).thenReturn(true);
when(config.services().firehose().tickIntervalSeconds()).thenReturn(10L);
FirehoseService firehose = new FirehoseService(factory, s3, new KinesisService(factory, region),
region, Clock.systemUTC(), config, mock(FirehoseParquetConverter.class),
mock(FirehoseLambdaTransformer.class));
for (String account : List.of(OWNER, CALLER)) {
request.setAccountId(account);
firehose.createDeliveryStream("us-east-1", account, "shared", null, List.of(), null, null);
firehose.putRecord(account, "us-east-1", "shared", new Record(account.getBytes(UTF_8)));
firehose.flush(account, "us-east-1", "shared");
}
for (String account : List.of(OWNER, CALLER)) {
request.setAccountId(account);
assertTrue(s3.ownsBucket("floci-firehose-results"));
List<S3Object> delivered = s3.listObjects("floci-firehose-results", null, null, 100);
assertEquals(1, delivered.size());
assertEquals(account + "\n", new String(
s3.getObject("floci-firehose-results", delivered.getFirst().getKey()).getData(), UTF_8));
}
}
private Response delete(String version) {
return controller.deleteObject(BUCKET, "object.txt", null, version, uri, headers);
}
private <T> T inAccount(String account, Supplier<T> action) {
String previous = request.getAccountId();
request.setAccountId(account);
try {
return action.get();
} finally {
request.setAccountId(previous);
}
}
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@QuarkusTest
@TestProfile(S3IamEnforcementProfile.class)
class S3InternalLambdaCodeDownloadIntegrationTest {
private static final String REGION = "us-east-2";
private static final String TASKS_BUCKET = "awslambda-us-east-2-tasks";
@Inject
S3Service s3;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void bothAccountsDownloadTheirFunctionAndLayerCodeWithIamAndSignatureEnforcement() throws Exception {
String name = "owned-code-" + UUID.randomUUID().toString().substring(0, 8);
Map<String, byte[]> packages = new LinkedHashMap<>();
for (String account : List.of("481111110001", "481111110002")) {
byte[] archive = archive(account);
packages.put(account, archive);
String authorization = EnforcementFixtures.auth(account, REGION, "lambda");
cleanup.register(() -> RequestScopes.runAs(account, REGION, () -> {
if (s3.ownsBucket(TASKS_BUCKET)) {
s3.deleteBucket(TASKS_BUCKET);
}
assertFalse(s3.ownsBucket(TASKS_BUCKET));
}));
cleanup.register(() -> given().header("Authorization", authorization)
.delete("/2015-03-31/functions/" + name));
given().header("Authorization", authorization).contentType("application/json")
.body(Map.of("FunctionName", name, "Runtime", "nodejs20.x",
"Role", "arn:aws:iam::" + account + ":role/local-role", "Handler", "index.handler",
"Code", Map.of("ZipFile", Base64.getEncoder().encodeToString(archive))))
.post("/2015-03-31/functions").then().statusCode(201);
cleanup.register(() -> given().header("Authorization", authorization)
.delete("/2018-10-31/layers/" + name + "/versions/1"));
given().header("Authorization", authorization).contentType("application/json")
.body(Map.of("Content", Map.of("ZipFile", Base64.getEncoder().encodeToString(archive))))
.post("/2018-10-31/layers/" + name + "/versions").then().statusCode(201);
}
for (Map.Entry<String, byte[]> entry : packages.entrySet()) {
String account = entry.getKey();
String authorization = EnforcementFixtures.auth(account, REGION, "lambda");
String functionLocation = given().header("Authorization", authorization)
.get("/2015-03-31/functions/" + name).then().statusCode(200)
.extract().path("Code.Location");
String layerLocation = given().header("Authorization", authorization)
.get("/2018-10-31/layers/" + name + "/versions/1").then().statusCode(200)
.extract().path("Content.Location");
for (String location : List.of(functionLocation, layerLocation)) {
URI uri = URI.create(location);
assertArrayEquals(entry.getValue(), given().urlEncodingEnabled(false).get(location)
.then().statusCode(200).extract().asByteArray());
given().get(uri.getRawPath()).then().statusCode(403);
given().urlEncodingEnabled(false)
.get(location.replaceFirst("X-Amz-Signature=[0-9a-f]+",
"X-Amz-Signature=" + "0".repeat(64)))
.then().statusCode(403).body(containsString("SignatureDoesNotMatch"));
}
}
}
private static byte[] archive(String marker) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(("exports.handler = async () => '" + marker + "';").getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
}
}
@@ -0,0 +1,125 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusMock;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@QuarkusTest
class S3LegacyHeaderAccountIntegrationTest {
private static final String ACCOUNT = "000000000001";
private static final String LEGACY = "AWS " + ACCOUNT + ":local-signature";
private static final String MODERN = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ "/20261020/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=local-signature";
@Inject
RequestContext requestContext;
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void activeIamKeysSelectTheirOwnerAndInactiveKeysFallBack() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String user = "legacy-routing-" + suffix;
String bucket = "legacy-iam-routing-" + suffix;
String iamHeader = MODERN.replace("/s3/", "/iam/");
cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), iamHeader, user));
cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), MODERN, bucket));
given().header("Authorization", iamHeader).formParam("Action", "CreateUser")
.formParam("UserName", user).post("/").then().statusCode(200);
String accessKey = given().header("Authorization", iamHeader).formParam("Action", "CreateAccessKey")
.formParam("UserName", user).post("/").then().statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
String legacy = "AWS " + accessKey + ":local-signature";
try {
given().header("Authorization", legacy).put("/" + bucket).then().statusCode(200);
given().header("Authorization", legacy).body("iam-owned")
.put("/" + bucket + "/object.txt").then().statusCode(200);
given().header("Authorization", MODERN).get("/" + bucket + "/object.txt")
.then().statusCode(200).body(equalTo("iam-owned"));
given().header("Authorization", iamHeader).formParam("Action", "UpdateAccessKey")
.formParam("UserName", user).formParam("AccessKeyId", accessKey)
.formParam("Status", "Inactive").post("/").then().statusCode(200);
given().header("Authorization", legacy).get("/" + bucket + "/object.txt")
.then().statusCode(404).body(containsString("NoSuchBucket"));
} finally {
given().header("Authorization", MODERN).delete("/" + bucket + "/object.txt");
given().header("Authorization", MODERN).delete("/" + bucket);
given().header("Authorization", iamHeader).formParam("Action", "DeleteAccessKey")
.formParam("UserName", user).formParam("AccessKeyId", accessKey).post("/");
given().header("Authorization", iamHeader).formParam("Action", "DeleteUser")
.formParam("UserName", user).post("/");
}
}
@Test
void legacyS3HeadersShareTheModernOwnerAndDoNotLeakIntoTheNextRequest() {
String bucket = "legacy-account-" + UUID.randomUUID();
cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), MODERN, bucket));
given().header("Authorization", LEGACY).put("/" + bucket).then().statusCode(200);
try {
given().header("Authorization", LEGACY).body("owned-data")
.put("/" + bucket + "/object.txt").then().statusCode(200);
given().header("Authorization", MODERN).get("/" + bucket + "/object.txt")
.then().statusCode(200).body(equalTo("owned-data"));
given().get("/" + bucket + "/object.txt")
.then().statusCode(404).body(containsString("NoSuchBucket"));
given().header("Authorization", "AWS unknown-key:signature").get("/" + bucket + "/object.txt")
.then().statusCode(404).body(containsString("NoSuchBucket"));
given().header("Authorization", MODERN).get("/" + bucket + "/object.txt")
.then().statusCode(200).body(equalTo("owned-data"));
} finally {
given().header("Authorization", MODERN).delete("/" + bucket + "/object.txt");
given().header("Authorization", MODERN).delete("/" + bucket);
}
}
@Test
void legacyS3DataEventsCarryTheSameCredentialAndRequestAccount() {
AtomicReference<CloudTrailService.S3EventInput> recorded = new AtomicReference<>();
AtomicReference<String> eventAccount = new AtomicReference<>();
CloudTrailService cloudTrail = mock(CloudTrailService.class);
doAnswer(invocation -> {
recorded.set(invocation.getArgument(0));
eventAccount.set(requestContext.getAccountId());
return null;
}).when(cloudTrail).emitS3DataEvent(any());
QuarkusMock.installMockForType(cloudTrail, CloudTrailService.class);
String bucket = "legacy-event-" + UUID.randomUUID();
cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), MODERN, bucket));
given().header("Authorization", LEGACY).put("/" + bucket).then().statusCode(200);
try {
given().header("Authorization", LEGACY).body("owned-data")
.put("/" + bucket + "/object.txt").then().statusCode(200);
assertEquals(ACCOUNT, eventAccount.get());
assertEquals(ACCOUNT, recorded.get().accessKeyId());
assertEquals("PutObject", recorded.get().eventName());
} finally {
given().header("Authorization", MODERN).delete("/" + bucket + "/object.txt");
given().header("Authorization", MODERN).delete("/" + bucket);
}
}
}
@@ -198,7 +198,8 @@ class S3LifecycleServiceTest {
s3Service.applyLifecycleExpiration(Instant.now());
assertEquals(List.of("lifecycle"), notifications.functionNames);
assertEquals(List.of("arn:aws:lambda:us-east-1:000000000000:function:lifecycle"),
notifications.functionNames);
JsonNode record = new ObjectMapper().readTree(notifications.payloads.getFirst()).path("Records").get(0);
assertEquals("LifecycleExpiration:Delete", record.path("eventName").asText());
// The user guide's example names S3 itself, not a requester.
@@ -723,7 +723,8 @@ class S3ServiceTest {
"application/json", null);
assertEquals("ap-northeast-1", lambdaInvoker.region);
assertEquals("s3-notif-test", lambdaInvoker.functionName);
assertEquals("arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test",
lambdaInvoker.functionName);
assertEquals(InvocationType.Event, lambdaInvoker.type);
assertNotNull(lambdaInvoker.payload);
}
@@ -762,7 +763,8 @@ class S3ServiceTest {
service.putObject("test-bucket", "a.json", "{}".getBytes(StandardCharsets.UTF_8), "application/json", null);
assertEquals("s3-notif-test:PROD", lambdaInvoker.functionName);
assertEquals("arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test:PROD",
lambdaInvoker.functionName);
}
@Test