mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(s3): preserve bucket ownership across account routing (#6117)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
d7c139cb69
commit
88be39a7d4
33 files changed
+1209
-57
No files matched your search
@@ -4,13 +4,15 @@ Floci supports full per-account resource isolation out of the box. Resources cre
|
||||
|
||||
## How It Works
|
||||
|
||||
Every incoming request carries an AWS SigV4 `Authorization` header. Floci reads the **Access Key ID** (AKID) from that header and resolves the account in this order:
|
||||
Floci reads the **Access Key ID** (AKID) from a signed request's `Authorization` header and resolves the account in this order:
|
||||
|
||||
1. An exactly 12-digit AKID is used directly as the account ID.
|
||||
2. An active long-term IAM access key resolves to the account that owns it.
|
||||
3. A live STS temporary credential resolves to its recorded account.
|
||||
4. Any other key falls back to `FLOCI_DEFAULT_ACCOUNT_ID`.
|
||||
|
||||
Legacy S3 headers (`Authorization: AWS <access-key>:<signature>`) use the same account-routing rules when IAM enforcement is disabled. This supplies request metadata, not SigV2 authentication. S3 still rejects these headers when `FLOCI_AUTH_VALIDATE_SIGNATURES` or `FLOCI_SERVICES_S3_ENFORCE_AUTH` is enabled.
|
||||
|
||||
```
|
||||
Authorization: AWS4-HMAC-SHA256 Credential=111111111111/20260510/us-east-1/sqs/aws4_request, ...
|
||||
^^^^^^^^^^^^
|
||||
|
||||
+16
-1
@@ -313,6 +313,10 @@ for how this applies in China and GovCloud.
|
||||
|
||||
## Global Bucket Namespace
|
||||
|
||||
Object deletion, including `DeleteObjects` batches, uses the named bucket's owning account for
|
||||
stored objects, versions, annotations and notifications. Existing authorization checks still use
|
||||
the original caller, and `DeleteBucket` remains scoped to that caller's account.
|
||||
|
||||
By default S3 buckets are isolated per account (see [Multi-Account Isolation](../configuration/multi-account.md)),
|
||||
so two accounts can each hold a bucket with the same name. Set
|
||||
`FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE=true` to make bucket and object resolution span every
|
||||
@@ -320,7 +324,18 @@ account's partition — a bucket created in one account then resolves cross-acco
|
||||
where bucket names are globally unique. Enable this when a workload (for example an LZA log-archive or
|
||||
CDK asset bucket) is created in one account and read from another.
|
||||
|
||||
**Why the flag exists, and what it trades away.** Floci partitions every resource by the caller's account, which is the right model for services whose names are account-scoped in AWS. S3 bucket names are not: they are unique across all accounts, a bucket lives in exactly one owning account, and whether another account may touch it is decided by policy rather than by the name being unreachable. A hard per-account partition therefore lets two accounts hold different buckets under one name — a state AWS cannot reach — and makes a legitimate cross-account call fail with `NoSuchBucket` instead of being authorized or denied on its merits. With the flag on, a caller that names another account's bucket resolves it and only IAM and bucket-policy evaluation stand between the caller and the object: AWS-faithful, but stricter than the implicit isolation Floci gives you elsewhere — **provided both `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` (identity-policy checks, applied before the request reaches S3) and `FLOCI_SERVICES_S3_ENFORCE_AUTH` (the S3-specific flag that gates bucket-policy evaluation itself, in `S3Service.authorizeS3Read`/`authorizeS3Write`) are also `true`**. Both default to `false`, and bucket-policy evaluation in particular is a no-op while `FLOCI_SERVICES_S3_ENFORCE_AUTH` is off — regardless of the IAM flag — so in the default configuration enabling the global namespace does not trade per-account isolation for a policy-gated boundary — it removes the only isolation Floci gives S3 for that bucket and replaces it with nothing. Mutations are written back to the bucket's owning account rather than forked into the caller's, and `ListBuckets`/`ListObjects` stay owner-scoped, so the flag never reassigns ownership or leaks a bucket inventory. It is off by default — turn it on when emulating a multi-account estate whose real behaviour depends on the global namespace, and leave it off when the per-account partition is the isolation you are relying on. Account-scoped S3 state, notably the account-level Block Public Access configuration, is never widened by this flag. Note also that retrofitting a global namespace onto state that was previously partitioned per account means that if two accounts already hold a bucket under the same name — a state real AWS can't reach, but Floci's prior per-account isolation could — resolution picks whichever account's copy the backend happens to iterate to first; this is unlikely to be reachable on a fresh LZA-driven account structure, but is worth knowing if you enable the flag on an estate with pre-existing same-name buckets.
|
||||
Creating a bucket whose name another account owns returns `409 BucketAlreadyExists`. Concurrent
|
||||
creates and deletion share the same bucket-name lock. Recreating an owned bucket succeeds in
|
||||
`us-east-1` and returns `409 BucketAlreadyOwnedByYou` in other regions. `ListObjects` and
|
||||
`ListObjectsV2` read the named bucket's owner's objects; `ListBuckets` stays caller-scoped.
|
||||
The default per-account namespace and authentication settings are unchanged. Bucket-name reuse
|
||||
after deletion is immediate in Floci; AWS may temporarily return `409 OperationAborted`.
|
||||
|
||||
Floci-managed staging buckets for Lambda packages, Spectrum, Firehose conversion and CUR remain
|
||||
account scoped even when the global namespace is enabled. Their existing names and object paths are
|
||||
preserved; the internal creation path does not change public `CreateBucket` collision handling.
|
||||
|
||||
**Why the flag exists, and what it trades away.** Floci partitions every resource by the caller's account, which is the right model for services whose names are account-scoped in AWS. S3 bucket names are not: they are unique across all accounts, a bucket lives in exactly one owning account, and whether another account may touch it is decided by policy rather than by the name being unreachable. A hard per-account partition therefore lets two accounts hold different buckets under one name — a state AWS cannot reach — and makes a legitimate cross-account call fail with `NoSuchBucket` instead of being authorized or denied on its merits. With the flag on, a caller that names another account's bucket resolves it and only IAM and bucket-policy evaluation stand between the caller and the object: AWS-faithful, but stricter than the implicit isolation Floci gives you elsewhere — **provided both `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` (identity-policy checks, applied before the request reaches S3) and `FLOCI_SERVICES_S3_ENFORCE_AUTH` (the S3-specific flag that gates bucket-policy evaluation itself, in `S3Service.authorizeS3Read`/`authorizeS3Write`) are also `true`**. Both default to `false`, and bucket-policy evaluation in particular is a no-op while `FLOCI_SERVICES_S3_ENFORCE_AUTH` is off — regardless of the IAM flag — so in the default configuration enabling the global namespace does not trade per-account isolation for a policy-gated boundary — it removes the only isolation Floci gives S3 for that bucket and replaces it with nothing. Mutations are written back to the bucket's owning account rather than forked into the caller's, and `ListBuckets` stays caller-scoped while `ListObjects` and `ListObjectsV2` list the named bucket's owner-scoped objects, so the flag never reassigns ownership or leaks a bucket inventory. It is off by default — turn it on when emulating a multi-account estate whose real behaviour depends on the global namespace, and leave it off when the per-account partition is the isolation you are relying on. Account-scoped S3 state, notably the account-level Block Public Access configuration, is never widened by this flag. Note also that retrofitting a global namespace onto state that was previously partitioned per account means that if two accounts already hold a bucket under the same name — a state real AWS can't reach, but Floci's prior per-account isolation could — resolution picks whichever account's copy the backend happens to iterate to first; this is unlikely to be reachable on a fresh LZA-driven account structure, but is worth knowing if you enable the flag on an estate with pre-existing same-name buckets.
|
||||
|
||||
## Signature Verification
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Priorities;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -44,6 +46,9 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
/** The signing names S3 answers to; an S3 client expects S3's XML error document. */
|
||||
private static final Set<String> S3_SIGNING_NAMES = Set.of("s3", "s3express");
|
||||
|
||||
@Context
|
||||
ResourceInfo resourceInfo;
|
||||
|
||||
private final AccountResolver accountResolver;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RequestContext requestContext;
|
||||
@@ -52,18 +57,21 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
// (the AwsProtocolClaimFilter pattern). jakarta.inject.Provider is qualified inline because
|
||||
// this class also carries the JAX-RS @Provider annotation.
|
||||
private final jakarta.inject.Provider<EmulatorConfig> configProvider;
|
||||
private final jakarta.inject.Provider<ResolvedServiceCatalog> catalogProvider;
|
||||
|
||||
@Inject
|
||||
public AccountContextFilter(AccountResolver accountResolver,
|
||||
RegionResolver regionResolver,
|
||||
RequestContext requestContext,
|
||||
SessionAccountLookup sessionAccountLookup,
|
||||
jakarta.inject.Provider<EmulatorConfig> configProvider) {
|
||||
jakarta.inject.Provider<EmulatorConfig> configProvider,
|
||||
jakarta.inject.Provider<ResolvedServiceCatalog> catalogProvider) {
|
||||
this.accountResolver = accountResolver;
|
||||
this.regionResolver = regionResolver;
|
||||
this.requestContext = requestContext;
|
||||
this.sessionAccountLookup = sessionAccountLookup;
|
||||
this.configProvider = configProvider;
|
||||
this.catalogProvider = catalogProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -81,7 +89,10 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
if (rejectAmbiguousRegion(ctx, auth)) {
|
||||
return;
|
||||
}
|
||||
String akid = auth != null && !auth.isEmpty() ? accountResolver.extractAccessKeyId(auth) : null;
|
||||
String akid = resourceInfo != null && catalogProvider.get().byResourceClass(resourceInfo.getResourceClass())
|
||||
.map(ServiceDescriptor::acceptsLegacyAuthorization).orElse(false)
|
||||
&& !configProvider.get().services().iam().enforcementEnabled()
|
||||
? accountResolver.extractS3AccessKeyId(auth) : accountResolver.extractAccessKeyId(auth);
|
||||
if (akid != null) {
|
||||
requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
|
||||
requestContext.setAccessKeyId(akid);
|
||||
@@ -258,12 +269,13 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the account-resolution precedence. A 12-digit AKID is already reflected in
|
||||
* {@code resolvedDefault} (the account or default returned by {@link AccountResolver});
|
||||
* for any other key shape, an IAM or live-session lookup takes precedence before falling back.
|
||||
* Applies account resolution to header and presigned credentials, including legacy S3 keys.
|
||||
*/
|
||||
private String resolveAccount(String akid, String resolvedDefault) {
|
||||
if (akid != null && !akid.matches("\\d{12}")) {
|
||||
if (akid != null) {
|
||||
if (akid.matches("\\d{12}")) {
|
||||
return akid;
|
||||
}
|
||||
Optional<String> credentialAccount = sessionAccountLookup.resolveAccountId(akid);
|
||||
if (credentialAccount.isPresent()) {
|
||||
return credentialAccount.get();
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.util.regex.Pattern;
|
||||
public class AccountResolver {
|
||||
|
||||
private static final Pattern AKID_PATTERN = Pattern.compile("Credential=([^/]+)/");
|
||||
private static final Pattern S3_SIGV2_AKID_PATTERN = Pattern.compile("AWS ([^\\s:]+):[^\\s:]+");
|
||||
public static final String SIGV4_SCHEME = "AWS4-HMAC-SHA256";
|
||||
private static final String SIGV4_PREFIX = SIGV4_SCHEME + " ";
|
||||
private static final String SIGV4A_PREFIX = "AWS4-ECDSA-P256-SHA256 ";
|
||||
@@ -56,6 +57,16 @@ public class AccountResolver {
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
|
||||
/** Extracts S3 routing metadata without adding SigV2 authentication support. */
|
||||
public String extractS3AccessKeyId(String authorizationHeader) {
|
||||
String akid = extractAccessKeyId(authorizationHeader);
|
||||
if (akid != null || authorizationHeader == null) {
|
||||
return akid;
|
||||
}
|
||||
Matcher legacyS3 = S3_SIGV2_AKID_PATTERN.matcher(authorizationHeader.trim());
|
||||
return legacyS3.matches() ? legacyS3.group(1) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the account ID from an X-Amz-Credential value found in
|
||||
* presigned URL query parameters.
|
||||
|
||||
@@ -133,7 +133,7 @@ public class ResolvedServiceCatalog {
|
||||
5000L, AwsNamespaces.S3, ServiceProtocol.REST_XML,
|
||||
protocols(ServiceProtocol.REST_XML),
|
||||
// s3express: directory-bucket (S3 Express One Zone) clients sign with it
|
||||
Set.of(), Set.of("s3", "s3express"), Set.of(), Set.of(S3Controller.class)),
|
||||
Set.of(), Set.of("s3", "s3express"), Set.of(), Set.of(S3Controller.class)).withLegacyAuthorization(),
|
||||
descriptor("dynamodb", "dynamodb", config.services().dynamodb().enabled(), true,
|
||||
"dynamodb", storageMode(config.storage().services().dynamodb().mode(), config.storage().mode()),
|
||||
config.storage().services().dynamodb().flushIntervalMs(), null, ServiceProtocol.JSON,
|
||||
|
||||
@@ -17,9 +17,27 @@ public record ServiceDescriptor(
|
||||
Set<String> credentialScopes,
|
||||
Set<String> cborSdkServiceIds,
|
||||
Set<Class<?>> resourceClasses,
|
||||
Set<String> jsonOnlyTargetPrefixes
|
||||
Set<String> jsonOnlyTargetPrefixes,
|
||||
boolean acceptsLegacyAuthorization
|
||||
) {
|
||||
|
||||
public ServiceDescriptor(String externalKey, String configKey, boolean enabled, boolean includeInStatus,
|
||||
String storageKey, String storageMode, long storageFlushIntervalMs,
|
||||
String xmlNamespace, ServiceProtocol defaultProtocol,
|
||||
Set<ServiceProtocol> supportedProtocols, Set<String> targetPrefixes,
|
||||
Set<String> credentialScopes, Set<String> cborSdkServiceIds,
|
||||
Set<Class<?>> resourceClasses, Set<String> jsonOnlyTargetPrefixes) {
|
||||
this(externalKey, configKey, enabled, includeInStatus, storageKey, storageMode, storageFlushIntervalMs,
|
||||
xmlNamespace, defaultProtocol, supportedProtocols, targetPrefixes, credentialScopes,
|
||||
cborSdkServiceIds, resourceClasses, jsonOnlyTargetPrefixes, false);
|
||||
}
|
||||
|
||||
public ServiceDescriptor withLegacyAuthorization() {
|
||||
return new ServiceDescriptor(externalKey, configKey, enabled, includeInStatus, storageKey, storageMode,
|
||||
storageFlushIntervalMs, xmlNamespace, defaultProtocol, supportedProtocols, targetPrefixes,
|
||||
credentialScopes, cborSdkServiceIds, resourceClasses, jsonOnlyTargetPrefixes, true);
|
||||
}
|
||||
|
||||
public boolean supportsStorage() {
|
||||
return storageKey != null;
|
||||
}
|
||||
|
||||
@@ -182,11 +182,10 @@ public class ParquetEmitter {
|
||||
}
|
||||
}
|
||||
try {
|
||||
s3Service.createBucket(stagingBucket, defaultRegion);
|
||||
s3Service.createInternalBucket(stagingBucket, defaultRegion);
|
||||
} catch (AwsException e) {
|
||||
// BucketAlreadyOwnedByYou under race; safe to ignore.
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())
|
||||
&& !"BucketAlreadyExists".equals(e.getErrorCode())) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-3
@@ -518,10 +518,9 @@ public class FirehoseParquetConverter {
|
||||
|
||||
private void ensureStagingBucket() {
|
||||
try {
|
||||
s3Service.createBucket(stagingBucket, regionResolver.getDefaultRegion());
|
||||
s3Service.createInternalBucket(stagingBucket, regionResolver.getDefaultRegion());
|
||||
} catch (AwsException e) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())
|
||||
&& !"BucketAlreadyExists".equals(e.getErrorCode())) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1267,7 +1267,11 @@ public class FirehoseService implements ResourceProvider {
|
||||
? AwsArnUtils.regionOrDefault(stream.getDeliveryStreamARN(), regionResolver.getDefaultRegion())
|
||||
: regionResolver.getDefaultRegion();
|
||||
try {
|
||||
s3Service.createBucket(bucket, region);
|
||||
if (ownDestination) {
|
||||
s3Service.createBucket(bucket, region);
|
||||
} else {
|
||||
s3Service.createInternalBucket(bucket, region);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// The bucket usually exists already; a real problem with it surfaces on the write that follows.
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
@@ -27,7 +28,6 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriBuilder;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -53,12 +53,15 @@ public class LambdaController {
|
||||
private final LambdaService lambdaService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final PreSignedUrlGenerator presignGenerator;
|
||||
|
||||
@Inject
|
||||
public LambdaController(LambdaService lambdaService, RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
public LambdaController(LambdaService lambdaService, RegionResolver regionResolver, ObjectMapper objectMapper,
|
||||
PreSignedUrlGenerator presignGenerator) {
|
||||
this.lambdaService = lambdaService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.presignGenerator = presignGenerator;
|
||||
}
|
||||
|
||||
// ──────────────────────────── CreateFunction ────────────────────────────
|
||||
@@ -102,12 +105,14 @@ public class LambdaController {
|
||||
code.put("ImageUri", fn.getImageUri());
|
||||
code.put("ResolvedImageUri", fn.getImageUri());
|
||||
} else {
|
||||
// Path-style URL to the package in Floci's own S3, built from the
|
||||
// request so it targets the same endpoint the client is talking to.
|
||||
String location = UriBuilder.fromUri(uriInfo.getBaseUri())
|
||||
.path(LambdaService.tasksBucketName(region))
|
||||
.path(LambdaService.codeObjectKey(fn))
|
||||
.build().toString();
|
||||
String base = uriInfo.getBaseUri().toString();
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
String codeRegion = AwsArnUtils.regionOrDefault(fn.getFunctionArn(), region);
|
||||
String location = presignGenerator.generatePresignedUrl(base,
|
||||
LambdaService.tasksBucketName(codeRegion), LambdaService.codeObjectKey(fn),
|
||||
"GET", 0, codeRegion, LambdaService.ownerAccount(fn));
|
||||
code.put("Location", location);
|
||||
code.put("RepositoryType", "S3");
|
||||
}
|
||||
|
||||
@@ -3510,9 +3510,8 @@ public class LambdaService implements ResourceProvider {
|
||||
String bucket = tasksBucketName(region);
|
||||
try {
|
||||
try {
|
||||
s3Service.createBucket(bucket, region);
|
||||
s3Service.createInternalBucket(bucket, region);
|
||||
} catch (AwsException e) {
|
||||
// createBucket is idempotent only in us-east-1; elsewhere it 409s if it exists.
|
||||
if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
+1
-1
@@ -720,7 +720,7 @@ public class ExternalTableMaterializer {
|
||||
private void ensureScratchBucket() {
|
||||
boolean created = true;
|
||||
try {
|
||||
s3Service.createBucket(SCRATCH_BUCKET, config.defaultRegion());
|
||||
s3Service.createInternalBucket(SCRATCH_BUCKET, config.defaultRegion());
|
||||
} catch (AwsException exception) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(exception.getErrorCode())) {
|
||||
throw exception;
|
||||
|
||||
@@ -189,7 +189,8 @@ public class S3Controller {
|
||||
} catch (Exception e) {
|
||||
LOG.tracev(e, "CloudTrail: could not extract request context for S3 event {0}/{1}", bucket, key);
|
||||
}
|
||||
String akid = accountResolver.extractAccessKeyId(authHeader);
|
||||
String akid = config.services().iam().enforcementEnabled()
|
||||
? accountResolver.extractAccessKeyId(authHeader) : accountResolver.extractS3AccessKeyId(authHeader);
|
||||
String region = requestContext.getRegion() != null
|
||||
? requestContext.getRegion() : regionResolver.getDefaultRegion();
|
||||
cloudTrailService.emitS3DataEvent(CloudTrailService.S3EventInput.builder()
|
||||
|
||||
@@ -475,6 +475,19 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
public Bucket createBucket(String bucketName, String region, String requestedOwnership,
|
||||
String cannedAcl, String grantRead, String grantWrite,
|
||||
String grantFullControl, String grantReadAcp, String grantWriteAcp) {
|
||||
return createBucket(bucketName, region, requestedOwnership, cannedAcl, grantRead, grantWrite,
|
||||
grantFullControl, grantReadAcp, grantWriteAcp, false);
|
||||
}
|
||||
|
||||
/** Creates an account-scoped Floci staging bucket, independently of the public bucket namespace. */
|
||||
public Bucket createInternalBucket(String bucketName, String region) {
|
||||
return createBucket(bucketName, region, null, null, null, null, null, null, null, true);
|
||||
}
|
||||
|
||||
private Bucket createBucket(String bucketName, String region, String requestedOwnership,
|
||||
String cannedAcl, String grantRead, String grantWrite,
|
||||
String grantFullControl, String grantReadAcp, String grantWriteAcp,
|
||||
boolean internal) {
|
||||
requirePathSafeBucketName(bucketName);
|
||||
String ownership = requestedOwnership == null ? "BucketOwnerEnforced" : requestedOwnership;
|
||||
if (!OBJECT_OWNERSHIP_VALUES.contains(ownership)) {
|
||||
@@ -498,16 +511,29 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
throw new AwsException("InvalidBucketAclWithBlockPublicAccessError",
|
||||
"Bucket cannot have public ACLs set with BlockPublicAccess enabled", 400);
|
||||
}
|
||||
var existing = bucketStore.get(bucketName);
|
||||
// Share deletion's name lock so checking availability and publishing an owner are atomic.
|
||||
return withLock(multipartBucketLock(bucketName).writeLock(),
|
||||
() -> createBucketLocked(bucketName, region, ownership, requestedAcl, internal));
|
||||
}
|
||||
|
||||
private Bucket createBucketLocked(String bucketName, String region, String ownership, String requestedAcl,
|
||||
boolean internal) {
|
||||
Optional<Bucket> existing = bucketStore.get(bucketName);
|
||||
if (existing.isPresent()) {
|
||||
Bucket bucket = existing.get();
|
||||
if (isDefaultS3Region(bucket.getRegion()) && isDefaultS3Region(region)) {
|
||||
if (!internal && isDefaultS3Region(bucket.getRegion()) && isDefaultS3Region(region)) {
|
||||
LOG.infov("Bucket already exists in default region, treating CreateBucket as idempotent: {0}", bucketName);
|
||||
return bucket;
|
||||
}
|
||||
throw new AwsException("BucketAlreadyOwnedByYou",
|
||||
"Your previous request to create the named bucket succeeded and you already own it.", 409);
|
||||
}
|
||||
if (!internal && globalBucketNamespace && resolveBucketEntry(bucketName).isPresent()) {
|
||||
throw new AwsException("BucketAlreadyExists",
|
||||
"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.",
|
||||
409);
|
||||
}
|
||||
|
||||
Bucket bucket = new Bucket(bucketName);
|
||||
bucket.setRegion(region);
|
||||
@@ -1730,7 +1756,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
return false;
|
||||
}
|
||||
if (versionId == null && bucket.get().value().isVersioningEnabled()) {
|
||||
boolean currentIsVersioned = objectStore.get(objectKey(bucketName, key))
|
||||
boolean currentIsVersioned = resolveObjectForAccount(bucket.get().account(), objectKey(bucketName, key))
|
||||
.map(current -> current.getVersionId() != null)
|
||||
.orElse(true);
|
||||
if (currentIsVersioned) {
|
||||
@@ -2114,18 +2140,21 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
*/
|
||||
public S3Object deleteObject(String bucketName, String key, String versionId, boolean bypassGovernance,
|
||||
String ifMatch) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
Bucket bucket = ownedBucket.value();
|
||||
|
||||
// The bucket monitor serializes this against PutObject's annotation cleanup and the
|
||||
// annotation subresource writes, which hold the same monitor (storeObjectInternal
|
||||
// already runs under it via storeObject). The precondition is checked under it too,
|
||||
// so a concurrent overwrite cannot land between the check and the delete.
|
||||
synchronized (bucket) {
|
||||
checkDeletePrecondition(bucketName, key, ifMatch);
|
||||
return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance, OBJECT_REMOVED_EVENT);
|
||||
}
|
||||
return RequestScopes.callAs(ownedBucket.account(), () -> {
|
||||
synchronized (bucket) {
|
||||
checkDeletePrecondition(bucketName, key, ifMatch);
|
||||
return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance, OBJECT_REMOVED_EVENT);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2300,8 +2329,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* entry must not make that entry require {@code s3:BypassGovernanceRetention}.
|
||||
*/
|
||||
public boolean isGovernanceRetentionActive(String bucketName, String key, String versionId) {
|
||||
ensureBucketExists(bucketName);
|
||||
S3Object object = objectStore.get(versionStoreKey(bucketName, key, versionId))
|
||||
String bucketOwnerAccount = getBucketOwnerAccountId(bucketName);
|
||||
S3Object object = resolveObjectForAccount(bucketOwnerAccount, versionStoreKey(bucketName, key, versionId))
|
||||
.filter(existing -> isNamedVersion(existing, versionId))
|
||||
.orElse(null);
|
||||
return object != null
|
||||
@@ -2323,14 +2352,18 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
public ListObjectsResult listObjectsWithPrefixes(String bucketName, String prefix, String delimiter, int maxKeys,
|
||||
String continuationToken, String startAfter) {
|
||||
ensureBucketExists(bucketName);
|
||||
String bucketOwnerAccount = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404))
|
||||
.account();
|
||||
|
||||
String keyPrefix = bucketName + "/";
|
||||
String fullPrefix = prefix != null ? keyPrefix + prefix : keyPrefix;
|
||||
|
||||
// Filter out versioned entries (contain #v#) and delete markers
|
||||
List<S3Object> allObjects = objectStore.scan(key ->
|
||||
key.startsWith(fullPrefix) && !key.contains("#v#"))
|
||||
Predicate<String> keyFilter = key -> key.startsWith(fullPrefix) && !key.contains("#v#");
|
||||
List<S3Object> storedObjects = scanObjectsForAccount(bucketOwnerAccount, keyFilter);
|
||||
List<S3Object> allObjects = storedObjects
|
||||
.stream()
|
||||
.filter(obj -> !obj.isDeleteMarker())
|
||||
.toList();
|
||||
@@ -6454,7 +6487,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Invalid Lambda function ARN: " + ln.functionArn(), 400);
|
||||
}
|
||||
invokeLambda(lambdaRegion, functionName, eventJson.getBytes(StandardCharsets.UTF_8));
|
||||
invokeLambda(lambdaRegion, ln.functionArn(), eventJson.getBytes(StandardCharsets.UTF_8));
|
||||
LOG.debugv("Fired S3 event {0} to Lambda {1}", eventName, ln.functionArn());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to deliver S3 event to Lambda {0}: {1}", ln.functionArn(), e.getMessage());
|
||||
@@ -6835,7 +6868,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* Resolves a bucket for existence/access. With {@code globalBucketNamespace} enabled, the
|
||||
* lookup spans every account's partition (AWS bucket names are globally unique and reachable
|
||||
* cross-account); otherwise it stays scoped to the calling account. Write-side ownership
|
||||
* checks (CreateBucket, delete) intentionally do not use this — they remain account-scoped.
|
||||
* checks (CreateBucket, DeleteBucket) intentionally do not use this; they remain account-scoped.
|
||||
*/
|
||||
private Optional<Bucket> resolveBucket(String bucketName) {
|
||||
return resolveBucketEntry(bucketName).map(AccountAwareStorageBackend.OwnedEntry::value);
|
||||
@@ -6917,11 +6950,21 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
if (objectStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<S3Object> typed = (AccountAwareStorageBackend<S3Object>) aware;
|
||||
return typed.getForAccount(accountId, storeKey);
|
||||
return typed.getForAccount(accountId, storeKey)
|
||||
.or(() -> typed.getLegacyForAccount(accountId, storeKey));
|
||||
}
|
||||
return objectStore.get(storeKey);
|
||||
}
|
||||
|
||||
private List<S3Object> scanObjectsForAccount(String accountId, Predicate<String> keyFilter) {
|
||||
if (globalBucketNamespace && objectStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<S3Object> typed = (AccountAwareStorageBackend<S3Object>) aware;
|
||||
return typed.scanForAccount(accountId, keyFilter);
|
||||
}
|
||||
return objectStore.scan(keyFilter);
|
||||
}
|
||||
|
||||
private void putObjectForAccount(String accountId, String storeKey, S3Object object) {
|
||||
if (objectStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -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
|
||||
|
||||
+8
@@ -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());
|
||||
}
|
||||
}
|
||||
+2
@@ -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
|
||||
|
||||
+1
-1
@@ -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"));
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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));
|
||||
|
||||
+8
@@ -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>")
|
||||
|
||||
+179
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
|
||||
+39
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -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();
|
||||
}
|
||||
}
|
||||
+125
@@ -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
|
||||
|
||||
Reference in new issue
Block a user