feat(s3): opt-in global bucket namespace and replication config (#2640)

* feat(s3): bucket replication configuration round-trip

PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.

* fix(s3): resolve buckets cross-account under a global bucket namespace

S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.

Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.

* test(s3): guard getObject against torn reads under concurrent overwrite

LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.

* docs(s3): document the global bucket namespace flag

Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.

* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)

Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).

(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)

* fix(s3): persist account-level Block Public Access

The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.

Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.

clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().

* fix(s3): check x-amz-account-id against the caller on Block Public Access

The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.

AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.

One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.

Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.

* docs(s3): state the global bucket namespace trade-off explicitly

No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.

* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate

Upstream landed its own Put/Get/DeleteBucketReplication (ce4f6d1c4), which
duplicated the branch implementation. The branch copy stays because it goes
through mutateBucket (the caller-scoped mutation the LZA
Custom::S3PutBucketReplication path requires) and validates Role, Rule and
Destination/Bucket; upstream's root-element MalformedXML check is folded
into it so nothing upstream tested is lost. Duplicate Bucket field and
accessors removed.

* fix(s3): enforce the modeled AccountId pattern and ReplicationRule status enum

Account-level Block Public Access took x-amz-account-id as its storage
partition key after only a blank check, so a value outside the s3control
AccountId shape (^\d{12}$) filed a security configuration under a partition
no account could address again.

PutBucketReplication stored the document after checking only that a Role, a
Rule and a Destination/Bucket were present, so a rule with a missing or
out-of-enum Status round-tripped through GetBucketReplication as a document
AWS would have rejected. Both now answer the error the operation already
uses for its other input guards.

* fix(s3): resolve GetBucketReplication cross-account under the global bucket namespace

putBucketReplication and every other bucket-config mutation resolve cross-account
through mutateBucket/resolveBucket when globalBucketNamespace is enabled, but
getBucketReplication still called bucketStore.get(bucketName) directly. A
management-account caller could write a bucket's replication configuration
cross-account (mirroring LZA's Custom::S3PutBucketReplication path) but a
follow-up GetBucketReplication under the same caller saw NoSuchBucket instead of
the configuration it just stored.

RED test: getBucketReplicationResolvesCrossAccount in
S3GlobalBucketNamespaceTest failed with NoSuchBucket before this change.

* fix(s3): validate each replication rule's own destination bucket

PutBucketReplication checked that at least one Bucket appeared anywhere in the
document, then validated only Status per rule. A multi-rule document where only
one rule carried a Destination/Bucket satisfied that document-wide check and
round-tripped through GetBucketReplication as a configuration AWS would have
rejected as MalformedXML.

Destination elements appear in the same document order as their owning Rule
(extractGroupsMulti can't see nested Destination/Bucket as a Rule leaf), so
pairing the Destination list position-for-position with the Rule list and
requiring an equal count plus a non-blank Bucket in each enforces that every
rule carries its own destination.

RED test: putReplicationRejectsARuleWithoutItsOwnDestinationBucket in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): remove unreachable duplicate ?replication dispatch

The PUT and GET handlers each had two identical `if (hasQueryParam(uriInfo,
"replication"))` branches — a rebase artifact. The earlier branch in each
method always returns first, so the second was dead code that risked a future
routing change updating only one copy.

* docs(s3): expose global-bucket-namespace in the canonical application.yml

globalBucketNamespace() was documented in EmulatorConfig and in
docs/services/s3.md but absent from the s3 block in both application.yml
files, leaving the runtime configuration surface out of sync with what the
code and docs describe.

* test(s3): assert torn-read stress threads actually finish

The writer/reader threads were joined with a 30s timeout but never checked for
liveness afterward. A thread still running past the timeout could leak past
the test (hanging the suite) or let the assertions pass vacuously without that
thread's reads or writes having completed.

* fix(s3): reject malformed PutPublicAccessBlock bodies

s3control's PutPublicAccessBlockRequest requires PublicAccessBlockConfiguration,
but the controller normalized any body — null, empty, unparseable, or a
different root element entirely — into a valid configuration with every flag
defaulted to false via canonicalPublicAccessBlockXml. For an account-level
Block Public Access control, that silently disabled every protection on a bad
request instead of failing it.

Reject a body whose root element is not PublicAccessBlockConfiguration with
the same MalformedXML the bucket-level replication path already uses for this
class of error, before normalization runs.

RED test: putRejectsAMalformedOrWrongRootBody in
S3ControlAccountIdEnforcementTest got 200 instead of 400 before this change.

* fix(s3): validate replication destinations against their own rule, not the document total

Counting Rule and Destination elements document-wide and requiring the totals to match let a
rule with two Destinations balance a rule with none, satisfying the check while storing a
configuration AWS would reject as MalformedXML. Destination is Required: Yes directly on Rule, so
PutBucketReplication now walks the parsed element tree and requires each Rule to have exactly one
Destination of its own with a non-blank Bucket, instead of comparing counts across the whole
document.

* fix(s3): reject a replication destination with multiple Bucket elements

Destination.Bucket is a required scalar member (botocore
s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
child("Bucket") returns only the first match, so a Destination with two Bucket
children silently accepted the first and stored a document AWS would reject
as MalformedXML.

Count the Bucket children explicitly and require exactly one, instead of
taking child("Bucket")'s single match unconditionally.

RED test: putReplicationRejectsADestinationWithMultipleBucketElements in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): wire bucket-policy operations through cross-account resolution

getBucketPolicy/putBucketPolicy/deleteBucketPolicy still resolved via
bucketStore directly, unlike object read/write and replication, so a
management-account caller got NoSuchBucket on a member-owned bucket's
policy even with the global bucket namespace enabled. Route them
through resolveBucket/mutateBucket like the rest of the cross-account
paths, and document the IAM-enforcement dependency and the same-name
non-determinism case in the trade-off writeup.

* docs(s3): name the flag that actually gates bucket-policy evaluation

The trade-off write-up said global-bucket-namespace's IAM/bucket-policy
protection depends on FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED, but that flag
only gates identity-policy checks in IamEnforcementFilter before a request
reaches S3 — bucket-policy evaluation itself (S3Service.authorizeS3Read/
authorizeS3Write, which reads the stored bucket policy) is gated separately
by FLOCI_SERVICES_S3_ENFORCE_AUTH, which also defaults false. Name both
flags and make explicit that the S3-specific one is what actually turns
bucket-policy evaluation on or off.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 11:24:47 -04:00
1 parent f1ad306599
commit c96dc98065
17 files changed
+1515 -77

No files matched your search

@@ -17,6 +17,11 @@ import software.amazon.awssdk.services.s3control.model.ListTagsForResourceRespon
import software.amazon.awssdk.services.s3control.model.TagResourceRequest;
import software.amazon.awssdk.services.s3control.model.UntagResourceRequest;
import software.amazon.awssdk.services.s3control.model.S3ControlException;
import software.amazon.awssdk.services.s3control.model.PutPublicAccessBlockRequest;
import software.amazon.awssdk.services.s3control.model.GetPublicAccessBlockRequest;
import software.amazon.awssdk.services.s3control.model.GetPublicAccessBlockResponse;
import software.amazon.awssdk.services.s3control.model.DeletePublicAccessBlockRequest;
import software.amazon.awssdk.services.s3control.model.PublicAccessBlockConfiguration;
import java.util.List;
import java.util.Map;
@@ -240,4 +245,68 @@ class S3ControlTest {
assertThat(tags).containsEntry("PlainArn", "works");
}
// --- Account-level Block Public Access (s3control Put/Get/DeletePublicAccessBlock) ---
// Exercised by AWS LZA's Custom::PutPublicAccessBlock custom resource during LoggingStack deploy.
@Test
@Order(8)
@DisplayName("putPublicAccessBlock: account-level config is set and read back")
void putAndGetAccountPublicAccessBlock() {
s3control.putPublicAccessBlock(PutPublicAccessBlockRequest.builder()
.accountId(ACCOUNT_ID)
.publicAccessBlockConfiguration(PublicAccessBlockConfiguration.builder()
.blockPublicAcls(true)
.ignorePublicAcls(true)
.blockPublicPolicy(true)
.restrictPublicBuckets(true)
.build())
.build());
GetPublicAccessBlockResponse resp = s3control.getPublicAccessBlock(
GetPublicAccessBlockRequest.builder().accountId(ACCOUNT_ID).build());
PublicAccessBlockConfiguration cfg = resp.publicAccessBlockConfiguration();
assertThat(cfg.blockPublicAcls()).isTrue();
assertThat(cfg.ignorePublicAcls()).isTrue();
assertThat(cfg.blockPublicPolicy()).isTrue();
assertThat(cfg.restrictPublicBuckets()).isTrue();
}
@Test
@Order(9)
@DisplayName("putPublicAccessBlock: absent flags default to false")
void putAccountPublicAccessBlockPartialDefaultsFalse() {
s3control.putPublicAccessBlock(PutPublicAccessBlockRequest.builder()
.accountId(ACCOUNT_ID)
.publicAccessBlockConfiguration(PublicAccessBlockConfiguration.builder()
.blockPublicAcls(true)
.build())
.build());
PublicAccessBlockConfiguration cfg = s3control.getPublicAccessBlock(
GetPublicAccessBlockRequest.builder().accountId(ACCOUNT_ID).build())
.publicAccessBlockConfiguration();
assertThat(cfg.blockPublicAcls()).isTrue();
assertThat(cfg.restrictPublicBuckets()).isFalse();
}
@Test
@Order(10)
@DisplayName("deletePublicAccessBlock: removes account-level config (subsequent get 404s)")
void deleteAccountPublicAccessBlock() {
s3control.putPublicAccessBlock(PutPublicAccessBlockRequest.builder()
.accountId(ACCOUNT_ID)
.publicAccessBlockConfiguration(PublicAccessBlockConfiguration.builder()
.blockPublicAcls(true).build())
.build());
s3control.deletePublicAccessBlock(DeletePublicAccessBlockRequest.builder()
.accountId(ACCOUNT_ID).build());
assertThatThrownBy(() -> s3control.getPublicAccessBlock(
GetPublicAccessBlockRequest.builder().accountId(ACCOUNT_ID).build()))
.isInstanceOf(S3ControlException.class)
.satisfies(e -> assertThat(((S3ControlException) e).statusCode()).isEqualTo(404));
}
}
@@ -174,6 +174,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
|---|---|---|
| `FLOCI_SERVICES_S3_ENABLED` | `true` | Enable the S3 service |
| `FLOCI_SERVICES_S3_DEFAULT_PRESIGN_EXPIRY_SECONDS` | `3600` | Default pre-signed URL expiry when none is specified |
| `FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE` | `false` | When `true`, bucket/object resolution spans every account's partition so a bucket created in one account is visible cross-account (a single global namespace), matching real S3's global bucket names. Off by default keeps buckets isolated per account |
### DynamoDB
+6
View File
@@ -159,6 +159,12 @@ All services that use `StorageFactory` participate in account isolation automati
Background workers (Lambda event-source pollers, DynamoDB TTL sweeper, MSK readiness poller, OpenSearch readiness poller) iterate across all accounts internally and route writes back to the originating account. No cross-account data leaks through these async paths.
**S3 exception — global bucket namespace.** S3 buckets are isolated per account by default like every
other service, but real S3 bucket names are globally unique. Set
`FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE=true` to make bucket/object resolution span every account's
partition, so a bucket created in one account is visible cross-account — needed when a workload writes a
bucket in one account and reads it from another (see [S3](../services/s3.md#global-bucket-namespace)).
## Signature Validation
Floci does not currently perform general SigV4 validation for `Authorization` headers. Only the access key ID matters for account resolution, so the secret access key can be any non-empty string.
+18
View File
@@ -25,9 +25,12 @@
| **S3 Select** | SelectObjectContent |
| **Public Access Block** | PutPublicAccessBlock, GetPublicAccessBlock, DeletePublicAccessBlock |
| **Metrics** | PutBucketMetricsConfiguration, GetBucketMetricsConfiguration, ListBucketMetricsConfigurations, DeleteBucketMetricsConfiguration |
| **Replication** | PutBucketReplication, GetBucketReplication, DeleteBucketReplication |
**RestoreObject** is accepted but stubbed: Floci validates the request and returns `202 Accepted`, but no restore state machine runs.
**Replication** is configuration-only: the replication configuration is stored on the bucket and round-trips through `GetBucketReplication`, but no objects are actually replicated.
## Event Notifications
Browser and presigned POST uploads emit `s3:ObjectCreated:Post`, matching AWS S3. They do not emit
@@ -149,6 +152,21 @@ aws s3api select-object-content \
When `FLOCI_SERVICES_ATHENA_MOCK=true` is set, Athena queries are stubbed but floci-duck does **not** start. In that configuration, S3 Select uses the Java evaluator for CSV and JSON. Parquet queries will fail unless `FLOCI_SERVICES_DUCK_URL` points to an already-running floci-duck instance.
## Global Bucket Namespace
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
account's partition — a bucket created in one account then resolves cross-account, matching real S3
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.
## Account-Level Block Public Access
The s3control `PutPublicAccessBlock`, `GetPublicAccessBlock` and `DeletePublicAccessBlock` operations are keyed by the `x-amz-account-id` header, stored per account, and persisted like the rest of S3's state so a restart does not silently drop the control. As in AWS, the header must name the caller's own account; a mismatch returns `AccessDenied` (403). Floci keeps one deliberate exception: the configured default (management) account may act on any account, because Floci's launched Lambdas run on placeholder credentials that resolve to the management account instead of assuming a role in the target account — which is how LZA's `Custom::PutPublicAccessBlock` resource reaches this API.
## Not Implemented
These AWS S3 features have no handler in Floci. Calls will return an error (typically `404` or `NoSuchBucket`-style):
@@ -934,6 +934,37 @@ public interface EmulatorConfig {
@WithDefault("3600")
int defaultPresignExpirySeconds();
/**
* When true, S3 bucket/object existence resolution spans every account's partition,
* modelling AWS's globally-unique bucket namespace (a bucket owned by one account is
* reachable cross-account). Listing (ListBuckets/ListObjects) stays owner-scoped.
* Default false preserves per-account bucket isolation.
*
* <p><strong>Why this widening is deliberate, and what it costs.</strong> Floci's default
* is to partition 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 and partitions, a bucket lives in exactly one owning account, and
* whether another account may touch it is decided by policy, not by the name being
* unreachable. Emulating that with a hard per-account partition makes two accounts able to
* hold different buckets under one name — a state AWS cannot reach — and makes a legitimate
* cross-account call (LZA's central logging bucket, a custom-resource Lambda calling back
* under the management account) fail with {@code NoSuchBucket} instead of being authorized
* or denied on its merits. This flag opts into the AWS-faithful namespace instead.
*
* <p>The trade-off is that account partitioning stops being a second, implicit line of
* defence for S3: with the flag on, a caller that names another account's bucket resolves
* it, and only IAM/bucket-policy evaluation stands between the caller and the object —
* exactly as in AWS, but stricter than Floci's default elsewhere. Mutations are written
* back to the bucket's <em>owning</em> account rather than forked into the caller's, and
* listing stays 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.
*/
@WithDefault("false")
boolean globalBucketNamespace();
}
interface DynamoDbServiceConfig {
@@ -1,15 +1,20 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
@@ -44,10 +49,16 @@ public class S3ControlController {
private static final String AMZ_ID_2 = "x-amz-id-2";
private final S3Service s3Service;
private final Instance<RequestContext> requestContextInstance;
private final String defaultAccountId;
@Inject
public S3ControlController(S3Service s3Service) {
public S3ControlController(S3Service s3Service,
Instance<RequestContext> requestContextInstance,
EmulatorConfig config) {
this.s3Service = s3Service;
this.requestContextInstance = requestContextInstance;
this.defaultAccountId = config.defaultAccountId();
}
/**
@@ -114,6 +125,143 @@ public class S3ControlController {
return Response.ok(xml).build();
}
/**
* PutPublicAccessBlock — sets the account-level S3 Block Public Access configuration.
*
* <p>Account-scoped (keyed by the {@code x-amz-account-id} header), distinct from the
* bucket-level operation. AWS LZA's {@code Custom::PutPublicAccessBlock} custom resource
* calls this for every governed account during the LoggingStack deploy; without it the
* custom-resource Lambda reports FAILED and the stack rolls back.
*
* PUT /v20180820/configuration/publicAccessBlock
* Header: x-amz-account-id
* Body: {@code <PublicAccessBlockConfiguration>} with the four boolean flags
*/
@PUT
@Path("/configuration/publicAccessBlock")
@Consumes(MediaType.WILDCARD)
public Response putPublicAccessBlock(
@HeaderParam("x-amz-account-id") String accountId,
String body) {
try {
requireCallerMayActOnAccount(accountId);
if (!"PublicAccessBlockConfiguration".equals(XmlParser.rootElementName(body))) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
s3Service.putAccountPublicAccessBlock(accountId, canonicalPublicAccessBlockXml(body));
return Response.ok().build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
/**
* GetPublicAccessBlock — returns the account-level S3 Block Public Access configuration.
*
* GET /v20180820/configuration/publicAccessBlock
* Header: x-amz-account-id
*/
@GET
@Path("/configuration/publicAccessBlock")
public Response getPublicAccessBlock(
@HeaderParam("x-amz-account-id") String accountId) {
try {
requireCallerMayActOnAccount(accountId);
return Response.ok(s3Service.getAccountPublicAccessBlock(accountId)).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
/**
* DeletePublicAccessBlock — removes the account-level S3 Block Public Access configuration.
*
* DELETE /v20180820/configuration/publicAccessBlock
* Header: x-amz-account-id
*/
@DELETE
@Path("/configuration/publicAccessBlock")
public Response deletePublicAccessBlock(
@HeaderParam("x-amz-account-id") String accountId) {
try {
requireCallerMayActOnAccount(accountId);
s3Service.deleteAccountPublicAccessBlock(accountId);
return Response.noContent().build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
/**
* Rejects an {@code x-amz-account-id} that names an account the caller has no claim on.
*
* <p>Block Public Access is a security control, and the header alone decides which account's
* configuration an operation reads, overwrites or deletes. Without this check any caller could
* manage any account's configuration by setting one header. AWS s3control answers
* {@code AccessDenied} when the header does not match the caller's own account, because there
* a cross-account call is made with credentials assumed <em>into</em> the target account, so
* the header and the caller always agree.
*
* <p>The emulator keeps one deliberate exception: the configured default (management) account
* may act on any account. Floci's launched Lambdas run on placeholder credentials that resolve
* to the management account rather than assuming a role in the target account, so LZA's
* {@code Custom::PutPublicAccessBlock} resource legitimately arrives as management-caller,
* governed-account-header. This is the same allowance {@code S3Service.mutateBucket} already
* makes for {@code Custom::S3PutBucketReplication}. Every other cross-account combination is
* denied.
*
* <p>A blank header is left to the service, which raises the modelled {@code InvalidRequest}.
*/
private void requireCallerMayActOnAccount(String accountId) {
if (accountId == null || accountId.isBlank()) {
return;
}
String caller = callerAccountId();
if (accountId.equals(caller) || defaultAccountId.equals(caller)) {
return;
}
throw new AwsException("AccessDenied", "Access Denied", 403);
}
/**
* The caller's account as resolved by {@code AccountContextFilter}, falling back to the
* configured default outside a request scope — the same resolution
* {@code AccountAwareStorageBackend} uses to pick a storage partition.
*/
private String callerAccountId() {
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
if (accountId != null && !accountId.isBlank()) {
return accountId;
}
} catch (ContextNotActiveException ignored) {
// outside request scope — fall through to the default account
}
}
return defaultAccountId;
}
/**
* Normalises an incoming PublicAccessBlockConfiguration body into a canonical, namespaced
* document so read-back is well-formed regardless of the client's request formatting or
* namespace. Absent flags default to false, matching the AWS API.
*/
private static String canonicalPublicAccessBlockXml(String requestXml) {
String xml = requestXml == null ? "" : requestXml;
return new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("PublicAccessBlockConfiguration", AwsNamespaces.S3_CONTROL)
.elem("BlockPublicAcls", XmlParser.extractFirst(xml, "BlockPublicAcls", "false"))
.elem("IgnorePublicAcls", XmlParser.extractFirst(xml, "IgnorePublicAcls", "false"))
.elem("BlockPublicPolicy", XmlParser.extractFirst(xml, "BlockPublicPolicy", "false"))
.elem("RestrictPublicBuckets", XmlParser.extractFirst(xml, "RestrictPublicBuckets", "false"))
.end("PublicAccessBlockConfiguration")
.build();
}
/**
* TagResource — replaces all tags on the specified S3 bucket.
*
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -33,8 +34,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
@@ -91,6 +94,15 @@ public class S3Service implements Resettable, ResourceProvider {
}
private final ConcurrentHashMap<String, Map<Integer, byte[]>> memoryMultipartStore = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, MultipartUpload> multipartUploads = new ConcurrentHashMap<>();
// Account-level (S3 Control) Block Public Access config, one entry per AWS account.
// Distinct from the bucket-level configuration held on each Bucket. Block Public Access is a
// security control that LZA applies once per governed account, so it is StorageFactory-backed
// like every other piece of S3 state rather than held in memory: a restart must not silently
// drop it. Always addressed through the explicit *ForAccount overloads — the account comes
// from the validated x-amz-account-id header, and the account namespace here is never global
// (globalBucketNamespace widens bucket resolution only, never this).
private final AccountAwareStorageBackend<String> accountPublicAccessBlockStore;
private static final String ACCOUNT_PUBLIC_ACCESS_BLOCK_KEY = "publicAccessBlock";
private final SqsService sqsService;
private final SnsService snsService;
@@ -104,6 +116,7 @@ public class S3Service implements Resettable, ResourceProvider {
private final ObjectMapper objectMapper;
private final boolean enforceAuth;
private final IamService iamService;
private final boolean globalBucketNamespace;
@Inject
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
@@ -121,13 +134,17 @@ public class S3Service implements Resettable, ResourceProvider {
storageFactory.create("s3", "s3-objects.json",
new TypeReference<Map<String, S3Object>>() {
}),
storageFactory.create("s3", "s3-account-public-access-block.json",
new TypeReference<Map<String, String>>() {
}),
Path.of(config.storage().persistentPath()).resolve("s3"),
"memory".equals(config.storage().services().s3().mode().orElse(config.storage().mode())),
sqsService, snsService, null, lambdaServiceProvider, null,
eventBridgeService, s3UpdatedEvent,
regionResolver,
config.effectiveBaseUrl(), objectMapper,
config.services().s3().enforceAuth(), iamService
config.services().s3().enforceAuth(), iamService,
config.services().s3().globalBucketNamespace()
);
}
@@ -137,8 +154,28 @@ public class S3Service implements Resettable, ResourceProvider {
S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
Path dataRoot, boolean inMemory) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null);
this(bucketStore, objectStore, defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, false);
}
/** Package-private constructor for testing account-level Block Public Access persistence. */
S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
AccountAwareStorageBackend<String> accountPublicAccessBlockStore,
Path dataRoot, boolean inMemory) {
this(bucketStore, objectStore, accountPublicAccessBlockStore,
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, false);
}
/** Package-private constructor for testing the global-bucket-namespace resolution flag. */
S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
Path dataRoot, boolean inMemory, boolean globalBucketNamespace) {
this(bucketStore, objectStore, defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, globalBucketNamespace);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -146,8 +183,9 @@ public class S3Service implements Resettable, ResourceProvider {
Path dataRoot, boolean inMemory,
LambdaService lambdaService,
RegionResolver regionResolver) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, lambdaService, null, null, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);
this(bucketStore, objectStore, defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, lambdaService, null, null, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null, false);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -155,12 +193,19 @@ public class S3Service implements Resettable, ResourceProvider {
Path dataRoot, boolean inMemory,
LambdaInvoker lambdaInvoker,
RegionResolver regionResolver) {
this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, lambdaInvoker, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);
this(bucketStore, objectStore, defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, lambdaInvoker, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null, false);
}
/** In-memory account-level Block Public Access store for the package-private test constructors. */
private static AccountAwareStorageBackend<String> defaultAccountPublicAccessBlockStore() {
return AccountAwareStorageBackend.inMemory("000000000000");
}
private S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
AccountAwareStorageBackend<String> accountPublicAccessBlockStore,
Path dataRoot, boolean inMemory, SqsService sqsService, SnsService snsService,
LambdaService lambdaService,
Instance<LambdaService> lambdaServiceProvider,
@@ -168,9 +213,10 @@ public class S3Service implements Resettable, ResourceProvider {
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
boolean enforceAuth, IamService iamService) {
boolean enforceAuth, IamService iamService, boolean globalBucketNamespace) {
this.bucketStore = bucketStore;
this.objectStore = objectStore;
this.accountPublicAccessBlockStore = accountPublicAccessBlockStore;
this.dataRoot = dataRoot;
this.inMemory = inMemory;
this.sqsService = sqsService;
@@ -185,6 +231,7 @@ public class S3Service implements Resettable, ResourceProvider {
this.objectMapper = objectMapper;
this.enforceAuth = enforceAuth;
this.iamService = iamService;
this.globalBucketNamespace = globalBucketNamespace;
if (!inMemory) {
try {
Files.createDirectories(dataRoot);
@@ -387,7 +434,7 @@ public class S3Service implements Resettable, ResourceProvider {
private S3Object storeObject(String bucketName, String key, byte[] data,
String contentType, Map<String, String> metadata,
S3Checksum checksum, List<Part> parts, PutObjectOptions options) {
Bucket bucket = bucketStore.get(bucketName)
Bucket bucket = resolveBucket(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
synchronized (bucket) {
@@ -729,7 +776,7 @@ public class S3Service implements Resettable, ResourceProvider {
private boolean readableObjectExists(String bucketName, String key) {
ensureBucketExists(bucketName);
return objectStore.get(objectKey(bucketName, key))
return resolveObject(objectKey(bucketName, key))
.filter(object -> !object.isDeleteMarker())
.isPresent();
}
@@ -929,7 +976,7 @@ public class S3Service implements Resettable, ResourceProvider {
ensureBucketExists(bucketName);
String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
S3Object object = objectStore.get(storeKey)
S3Object object = resolveObject(storeKey)
.orElseThrow(() -> versionId != null
? new AwsException("NoSuchVersion", "The specified version does not exist.", 404)
: new AwsException("NoSuchKey", "The specified key does not exist.", 404));
@@ -1419,7 +1466,7 @@ public class S3Service implements Resettable, ResourceProvider {
public String getBucketRegion(String bucketName) {
ensureBucketExists(bucketName);
return bucketStore.get(bucketName).map(Bucket::getRegion).orElse(null);
return resolveBucket(bucketName).map(Bucket::getRegion).orElse(null);
}
// --- Batch Delete ---
@@ -2139,7 +2186,7 @@ public class S3Service implements Resettable, ResourceProvider {
// ──────────────────────────── Policy, CORS, Lifecycle, ACL ────────────────────────────
public String getBucketPolicy(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
Bucket bucket = resolveBucket(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
if (bucket.getPolicy() == null) {
throw new AwsException("NoSuchBucketPolicy", "The bucket policy does not exist", 404);
@@ -2148,17 +2195,11 @@ public class S3Service implements Resettable, ResourceProvider {
}
public void putBucketPolicy(String bucketName, String policy) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
bucket.setPolicy(policy);
bucketStore.put(bucketName, bucket);
mutateBucket(bucketName, bucket -> bucket.setPolicy(policy));
}
public void deleteBucketPolicy(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
bucket.setPolicy(null);
bucketStore.put(bucketName, bucket);
mutateBucket(bucketName, bucket -> bucket.setPolicy(null));
}
public String getBucketCors(String bucketName) {
@@ -2405,6 +2446,49 @@ public class S3Service implements Resettable, ResourceProvider {
bucketStore.put(bucketName, bucket);
}
// --- Account-level (S3 Control) Public Access Block ---
// AWS s3control PutPublicAccessBlock / GetPublicAccessBlock / DeletePublicAccessBlock,
// keyed by AccountId (from the x-amz-account-id header). AWS LZA's
// Custom::PutPublicAccessBlock custom resource drives these during the LoggingStack deploy.
// S3ControlController checks the header against the caller before any of these run.
public void putAccountPublicAccessBlock(String accountId, String configXml) {
accountPublicAccessBlockStore.putForAccount(
requireAccountId(accountId), ACCOUNT_PUBLIC_ACCESS_BLOCK_KEY, configXml);
}
public String getAccountPublicAccessBlock(String accountId) {
return accountPublicAccessBlockStore
.getForAccount(requireAccountId(accountId), ACCOUNT_PUBLIC_ACCESS_BLOCK_KEY)
.orElseThrow(() -> new AwsException("NoSuchPublicAccessBlockConfiguration",
"The public access block configuration was not found", 404));
}
public void deleteAccountPublicAccessBlock(String accountId) {
accountPublicAccessBlockStore.deleteForAccount(
requireAccountId(accountId), ACCOUNT_PUBLIC_ACCESS_BLOCK_KEY);
}
/** The s3control {@code AccountId} shape: {@code pattern ^\d{12}$}. */
private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("\\d{12}");
/**
* The account id is the storage partition key for every account-level Block Public Access
* operation, so a value outside the modelled shape would file a security configuration under
* a partition no account can address again. Reject it before it reaches the store.
*/
private static String requireAccountId(String accountId) {
if (accountId == null || accountId.isBlank()) {
throw new AwsException("InvalidRequest",
"The x-amz-account-id header is required.", 400);
}
if (!ACCOUNT_ID_PATTERN.matcher(accountId).matches()) {
throw new AwsException("InvalidRequest",
"The x-amz-account-id header must be a 12-digit AWS account ID.", 400);
}
return accountId;
}
public String getBucketOwnershipControls(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
@@ -2429,6 +2513,88 @@ public class S3Service implements Resettable, ResourceProvider {
bucketStore.put(bucketName, bucket);
}
public String getBucketReplication(String bucketName) {
Bucket bucket = resolveBucket(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
if (bucket.getReplicationConfiguration() == null) {
throw new AwsException("ReplicationConfigurationNotFoundError",
"The replication configuration was not found", 404);
}
return bucket.getReplicationConfiguration();
}
/**
* Stores the bucket replication configuration for round-trip fidelity. The document is
* validated minimally (a {@code Role} and at least one {@code Rule} with a
* {@code Destination/Bucket}) and stored verbatim; Floci performs no actual replication.
*/
public void putBucketReplication(String bucketName, String replicationXml) {
mutateBucket(bucketName, bucket -> {
if (!"ReplicationConfiguration".equals(XmlParser.rootElementName(replicationXml))) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
String role = XmlParser.extractFirst(replicationXml, "Role", null);
List<Map<String, List<String>>> rules = XmlParser.extractGroupsMulti(replicationXml, "Rule");
// A document-wide count of Rule vs Destination elements can't tell a well-formed
// document from one where a rule has two Destinations and another has none (the
// totals still balance). Destination is a direct child of Rule, so walking the parsed
// element tree and inspecting each Rule's own children is the only way to require
// that every rule carries exactly its own destination.
XmlParser.XmlElement root = XmlParser.extractElementTree(replicationXml, "ReplicationConfiguration");
List<XmlParser.XmlElement> ruleElements = root == null
? List.of()
: root.children().stream().filter(c -> "Rule".equals(c.name())).toList();
if (role == null || role.isBlank() || ruleElements.isEmpty()) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
// ReplicationRule/Status is Required: Yes with enum Enabled|Disabled. Storing an
// out-of-enum status would have GetBucketReplication echo back a document AWS
// would never have accepted.
for (Map<String, List<String>> rule : rules) {
List<String> statuses = rule.getOrDefault("Status", List.of());
if (statuses.size() != 1 || !REPLICATION_RULE_STATUSES.contains(statuses.get(0))) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against "
+ "our published schema.", 400);
}
}
// Destination is Required: Yes on Rule, and ReplicationRuleAndOperator/Destination.Bucket
// is Required: Yes on Destination — checked against each rule's own children, not the
// document as a whole.
for (XmlParser.XmlElement ruleElement : ruleElements) {
List<XmlParser.XmlElement> ruleDestinations = ruleElement.children().stream()
.filter(c -> "Destination".equals(c.name())).toList();
// Bucket is a required *scalar* member of Destination (botocore
// s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
// child("Bucket") returns only the first match, so a Destination with two Bucket
// elements must be counted explicitly rather than silently accepting the first.
List<XmlParser.XmlElement> bucketElements = ruleDestinations.size() == 1
? ruleDestinations.get(0).children().stream()
.filter(c -> "Bucket".equals(c.name())).toList()
: List.of();
XmlParser.XmlElement bucketElement = bucketElements.size() == 1
? bucketElements.get(0) : null;
if (bucketElement == null || bucketElement.text().isBlank()) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against "
+ "our published schema.", 400);
}
}
bucket.setReplicationConfiguration(replicationXml);
});
}
/** The {@code ReplicationRuleStatus} enum from the S3 model. */
private static final Set<String> REPLICATION_RULE_STATUSES = Set.of("Enabled", "Disabled");
public void deleteBucketReplication(String bucketName) {
mutateBucket(bucketName, bucket -> bucket.setReplicationConfiguration(null));
}
/**
* Stores the bucket Request Payment configuration. AWS only allows the values
* {@code BucketOwner} and {@code Requester}; we accept either and reject anything
@@ -2513,42 +2679,6 @@ public class S3Service implements Resettable, ResourceProvider {
.build();
}
/**
* Stores the bucket replication configuration verbatim. Floci does not model
* replication behavior — the configuration is only stored and echoed back,
* which is what the SDK and the Terraform provider need. The
* ReplicationConfiguration root is required, so a body that does not parse
* to one is rejected with {@code MalformedXML}.
*/
public void putBucketReplication(String bucketName, String replicationXml) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
if (!"ReplicationConfiguration".equals(XmlParser.rootElementName(replicationXml))) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
bucket.setReplicationConfiguration(replicationXml);
bucketStore.put(bucketName, bucket);
}
public String getBucketReplication(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
if (bucket.getReplicationConfiguration() == null) {
throw new AwsException("ReplicationConfigurationNotFoundError",
"The replication configuration was not found", 404);
}
return bucket.getReplicationConfiguration();
}
public void deleteBucketReplication(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
bucket.setReplicationConfiguration(null);
bucketStore.put(bucketName, bucket);
}
public void restoreObject(String bucketName, String key, String versionId, String restoreXml) {
// Validation only - stub implementation
getObject(bucketName, key, versionId);
@@ -3163,12 +3293,72 @@ public class S3Service implements Resettable, ResourceProvider {
}
private void ensureBucketExists(String bucketName) {
if (bucketStore.get(bucketName).isEmpty()) {
if (resolveBucket(bucketName).isEmpty()) {
throw new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404);
}
}
/**
* 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.
*/
private Optional<Bucket> resolveBucket(String bucketName) {
if (globalBucketNamespace && bucketStore instanceof AccountAwareStorageBackend<?> aware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<Bucket> typed = (AccountAwareStorageBackend<Bucket>) aware;
return typed.findAnyAccount(bucketName);
}
return bucketStore.get(bucketName);
}
/**
* Resolves an existing bucket and applies a configuration mutation, persisting it back to the
* bucket's <em>owning</em> account partition. With {@code globalBucketNamespace} enabled the
* bucket is resolved cross-account (mirroring {@link #resolveBucket}) and written back to its
* owner via {@link AccountAwareStorageBackend#putForAccount} — so a cross-account custom-resource
* caller (e.g. LZA's {@code Custom::S3PutBucketReplication} Lambda, which calls back under the
* management-account context) cannot fork a phantom bucket into its own partition or silently
* drop the config on the real bucket. With the flag off this is exactly the original
* account-scoped get-mutate-put.
*
* <p>The {@code mutation} runs after existence is established and before the write-back, so it
* may perform bucket-dependent validation and throw (e.g. {@code MalformedXML}); a throw skips
* the write, matching the original methods' fail-before-persist behavior.
*/
private void mutateBucket(String bucketName, java.util.function.Consumer<Bucket> mutation) {
if (globalBucketNamespace && bucketStore instanceof AccountAwareStorageBackend<?> aware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<Bucket> typed = (AccountAwareStorageBackend<Bucket>) aware;
AccountAwareStorageBackend.OwnedEntry<Bucket> owned = typed.findAnyAccountEntry(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
mutation.accept(owned.value());
typed.putForAccount(owned.account(), bucketName, owned.value());
} else {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
mutation.accept(bucket);
bucketStore.put(bucketName, bucket);
}
}
/**
* Resolves an object for read access. Mirrors {@link #resolveBucket}: cross-account when
* {@code globalBucketNamespace} is enabled, otherwise account-scoped.
*/
private Optional<S3Object> resolveObject(String storeKey) {
if (globalBucketNamespace && objectStore instanceof AccountAwareStorageBackend<?> aware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<S3Object> typed = (AccountAwareStorageBackend<S3Object>) aware;
return typed.findAnyAccount(storeKey);
}
return objectStore.get(storeKey);
}
private String objectKey(String bucketName, String key) {
return bucketName + "/" + key;
}
@@ -3310,8 +3500,7 @@ public class S3Service implements Resettable, ResourceProvider {
ReentrantLock lock = diskFileLock(filePath);
lock.lock();
try {
Files.createDirectories(filePath.getParent());
Files.write(filePath, data);
atomicWrite(filePath, data);
} catch (IOException e) {
throw new UncheckedIOException("Failed to write versioned S3 object file", e);
} finally {
@@ -3339,8 +3528,7 @@ public class S3Service implements Resettable, ResourceProvider {
ReentrantLock lock = diskFileLock(filePath);
lock.lock();
try {
Files.createDirectories(filePath.getParent());
Files.write(filePath, data);
atomicWrite(filePath, data);
} catch (IOException e) {
throw new UncheckedIOException("Failed to write S3 object file", e);
} finally {
@@ -3348,6 +3536,34 @@ public class S3Service implements Resettable, ResourceProvider {
}
}
/**
* Writes {@code data} to {@code filePath} such that a concurrent reader ({@link #readFile})
* always observes either the complete previous file or the complete new one — never a
* truncated view. {@code Files.write} truncates-then-writes in place, so a reader that opens
* the path mid-write reads a short or empty file; under LZA's Bootstrap fan-out that torn
* read surfaced as an empty {@code src-Config} secondary source. Writing to a unique sibling
* temp file and atomically renaming it over the target closes that window. The temp name is
* unique per call so concurrent writers to the same key never clobber each other's temp file;
* whichever rename lands last wins, and every rename is all-or-nothing.
*/
private void atomicWrite(Path filePath, byte[] data) throws IOException {
Files.createDirectories(filePath.getParent());
Path tmp = filePath.resolveSibling(filePath.getFileName() + ".tmp-" + UUID.randomUUID());
try {
Files.write(tmp, data);
try {
Files.move(tmp, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
// Rare filesystems (some network mounts) reject ATOMIC_MOVE; fall back to a plain
// replace. This narrows but does not fully close the window — acceptable only
// because the default overlay/ext filesystems used here support atomic rename.
Files.move(tmp, filePath, StandardCopyOption.REPLACE_EXISTING);
}
} finally {
Files.deleteIfExists(tmp);
}
}
private byte[] readFile(String bucketName, String key) {
if (inMemory) {
return memoryDataStore.get(physicalKey(bucketName, key));
@@ -25,9 +25,9 @@ public class Bucket {
private String transitionDefaultMinimumObjectSize; // x-amz-transition-default-minimum-object-size header value
private String acl; // XML representation or JSON stub
private String encryptionConfiguration; // XML string
private String replicationConfiguration; // XML string
private String publicAccessBlockConfiguration; // XML string
private String ownershipControlsConfiguration; // XML string
private String replicationConfiguration; // XML string; null until first PUT
private String requestPaymentPayer; // "BucketOwner" (default) or "Requester"; null until first PUT
private String accelerateStatus; // "Enabled" or "Suspended"; null until first PUT
private String region;
@@ -99,6 +99,9 @@ public class Bucket {
public String getEncryptionConfiguration() { return encryptionConfiguration; }
public void setEncryptionConfiguration(String encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; }
public String getReplicationConfiguration() { return replicationConfiguration; }
public void setReplicationConfiguration(String replicationConfiguration) { this.replicationConfiguration = replicationConfiguration; }
public String getPublicAccessBlockConfiguration() { return publicAccessBlockConfiguration; }
public void setPublicAccessBlockConfiguration(String publicAccessBlockConfiguration) {
this.publicAccessBlockConfiguration = publicAccessBlockConfiguration;
@@ -109,10 +112,6 @@ public class Bucket {
this.ownershipControlsConfiguration = ownershipControlsConfiguration;
}
public String getReplicationConfiguration() { return replicationConfiguration; }
public void setReplicationConfiguration(String replicationConfiguration) {
this.replicationConfiguration = replicationConfiguration;
}
public String getRequestPaymentPayer() { return requestPaymentPayer; }
public void setRequestPaymentPayer(String requestPaymentPayer) { this.requestPaymentPayer = requestPaymentPayer; }
+1
View File
@@ -238,6 +238,7 @@ floci:
enabled: true
enforce-auth: false
default-presign-expiry-seconds: 3600
global-bucket-namespace: false
dynamodb:
enabled: true
sns:
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Account-level Block Public Access is a security control that AWS LZA sets once per governed
* account during the LoggingStack deploy; a resumed pipeline does not re-run
* {@code Custom::PutPublicAccessBlock}. It must therefore survive a restart rather than living
* only in process memory.
*/
class S3AccountPublicAccessBlockPersistenceTest {
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String GOVERNED_ACCOUNT = "452743914166";
private static final String CONFIG_XML =
"<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
+ "<RestrictPublicBuckets>true</RestrictPublicBuckets>"
+ "</PublicAccessBlockConfiguration>";
@Test
void accountConfigurationSurvivesRestart(@TempDir Path dir) {
S3Service first = newService(dir);
first.putAccountPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
first.putAccountPublicAccessBlock(DEFAULT_ACCOUNT, "<PublicAccessBlockConfiguration/>");
S3Service restarted = newService(dir);
assertEquals(CONFIG_XML, restarted.getAccountPublicAccessBlock(GOVERNED_ACCOUNT));
assertEquals("<PublicAccessBlockConfiguration/>",
restarted.getAccountPublicAccessBlock(DEFAULT_ACCOUNT));
}
@Test
void deletedAccountConfigurationStaysDeletedAcrossRestart(@TempDir Path dir) {
S3Service first = newService(dir);
first.putAccountPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
first.deleteAccountPublicAccessBlock(GOVERNED_ACCOUNT);
S3Service restarted = newService(dir);
AwsException ex = assertThrows(AwsException.class,
() -> restarted.getAccountPublicAccessBlock(GOVERNED_ACCOUNT));
assertEquals("NoSuchPublicAccessBlockConfiguration", ex.getErrorCode());
}
private S3Service newService(Path dir) {
PersistentStorage<String, String> backend = new PersistentStorage<>(
dir.resolve("s3-account-public-access-block.json"),
new TypeReference<Map<String, String>>() {});
backend.load();
return new S3Service(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new AccountAwareStorageBackend<>(backend, null, DEFAULT_ACCOUNT),
dir.resolve("s3"),
false);
}
}
@@ -0,0 +1,112 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Account-level (S3 Control) Block Public Access.
*
* <p>AWS LZA's {@code Custom::PutPublicAccessBlock} custom resource sets account-wide
* S3 Block Public Access via the s3control API ({@code PutPublicAccessBlock} keyed by
* {@code AccountId}, distinct from the bucket-level operation). This is what the
* LoggingStack deploy exercises for every governed account.
*/
class S3AccountPublicAccessBlockTest {
@TempDir
Path tempDir;
private S3Service s3Service;
@BeforeEach
void setUp() {
Path dataRoot = tempDir.resolve("s3");
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot, false);
}
@Test
void putThenGetAccountPublicAccessBlockRoundTrips() {
String xml = "<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
+ "</PublicAccessBlockConfiguration>";
s3Service.putAccountPublicAccessBlock("452743914166", xml);
assertEquals(xml, s3Service.getAccountPublicAccessBlock("452743914166"));
}
@Test
void accountConfigsAreIsolatedPerAccount() {
s3Service.putAccountPublicAccessBlock("452743914166", "<a/>");
s3Service.putAccountPublicAccessBlock("000000000000", "<b/>");
assertEquals("<a/>", s3Service.getAccountPublicAccessBlock("452743914166"));
assertEquals("<b/>", s3Service.getAccountPublicAccessBlock("000000000000"));
}
@Test
void getAccountPublicAccessBlockThrowsNoSuchWhenUnset() {
AwsException ex = assertThrows(AwsException.class,
() -> s3Service.getAccountPublicAccessBlock("000000000000"));
assertEquals("NoSuchPublicAccessBlockConfiguration", ex.getErrorCode());
}
@Test
void deleteAccountPublicAccessBlockRemovesConfig() {
s3Service.putAccountPublicAccessBlock("000000000000", "<x/>");
s3Service.deleteAccountPublicAccessBlock("000000000000");
assertThrows(AwsException.class,
() -> s3Service.getAccountPublicAccessBlock("000000000000"));
}
@Test
void deleteAccountPublicAccessBlockIsIdempotent() {
// Deleting an absent config must not throw (mirrors AWS 204 on repeat delete).
s3Service.deleteAccountPublicAccessBlock("000000000000");
}
@Test
void accountPublicAccessBlockRequiresAccountId() {
AwsException ex = assertThrows(AwsException.class,
() -> s3Service.putAccountPublicAccessBlock(" ", "<x/>"));
assertEquals("InvalidRequest", ex.getErrorCode());
}
/**
* The s3control {@code AccountId} shape is {@code pattern ^\d{12}$}. The header alone picks
* the storage partition every one of these operations reads, overwrites or deletes, so an
* unchecked value writes a configuration under a partition no account can ever address again.
*/
@Test
void accountPublicAccessBlockRejectsAMalformedAccountId() {
for (String bad : new String[] {"12345678901", "1234567890123", "00000000000a",
"arn:aws:iam::000000000000:root", "000000000000 "}) {
AwsException ex = assertThrows(AwsException.class,
() -> s3Service.putAccountPublicAccessBlock(bad, "<x/>"),
"expected rejection for account id: " + bad);
assertEquals("InvalidRequest", ex.getErrorCode());
}
}
@Test
void getAndDeleteAccountPublicAccessBlockAlsoRejectAMalformedAccountId() {
assertEquals("InvalidRequest", assertThrows(AwsException.class,
() -> s3Service.getAccountPublicAccessBlock("not-an-account")).getErrorCode());
assertEquals("InvalidRequest", assertThrows(AwsException.class,
() -> s3Service.deleteAccountPublicAccessBlock("not-an-account")).getErrorCode());
}
@Test
void clearLeavesAccountPublicAccessBlockToItsStorageBackend() {
// clear() resets only the in-process object/multipart maps. The account-level config now
// lives in a StorageFactory-backed store, whose lifecycle StorageFactory.clearAll() owns —
// same as the bucket and object stores, which clear() also deliberately leaves alone.
s3Service.putAccountPublicAccessBlock("000000000000", "<x/>");
s3Service.clear();
assertEquals("<x/>", s3Service.getAccountPublicAccessBlock("000000000000"));
}
}
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* In {@code hybrid}/filesystem storage mode (the default) an S3 object's bytes live on disk.
* LZA's Bootstrap stage fans out ~15 CodeBuild actions that each redundantly re-upload the
* same runtime-artifact keys ({@code codepipeline/<execId>/Source.zip}, {@code .../Config.zip})
* while other builds concurrently download those same keys to stage their source. A writer that
* truncates-then-writes a file is not atomic against a concurrent reader, so the reader can
* observe an empty or partial object — which surfaced downstream as an empty {@code src-Config}
* secondary source and {@code ENOENT: global-config.yaml}. getObject must therefore never return
* a torn view of a key that always holds the same full-size payload.
*/
class S3ConcurrentWriteReadTest {
@TempDir
Path tempDir;
@Test
void concurrentOverwriteNeverYieldsTornRead() throws Exception {
S3Service s3 = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("s3"), false);
String bucket = "codepipeline-artifacts";
String key = "codepipeline/exec-1/Config.zip";
s3.createBucket(bucket, "us-east-1");
// A sizable payload widens the truncate-then-write window so a torn read is observable.
byte[] payload = new byte[1 << 20];
for (int i = 0; i < payload.length; i++) {
payload[i] = (byte) (i * 31 + 7);
}
// Seed the key so readers never race a not-yet-created object (that is a separate concern).
s3.putObject(bucket, key, payload, "application/zip", Map.of());
int writers = 4;
int readers = 4;
int iterations = 400;
AtomicReference<String> firstTear = new AtomicReference<>();
AtomicInteger reads = new AtomicInteger();
volatileDone done = new volatileDone();
Thread[] threads = new Thread[writers + readers];
for (int w = 0; w < writers; w++) {
threads[w] = new Thread(() -> {
for (int i = 0; i < iterations && firstTear.get() == null; i++) {
s3.putObject(bucket, key, payload, "application/zip", Map.of());
}
done.count.incrementAndGet();
});
}
for (int r = 0; r < readers; r++) {
threads[writers + r] = new Thread(() -> {
while (done.count.get() < writers && firstTear.get() == null) {
S3Object obj = s3.getObject(bucket, key);
byte[] data = obj.getData();
reads.incrementAndGet();
if (data == null || data.length != payload.length) {
firstTear.compareAndSet(null,
"torn read: length=" + (data == null ? "null" : data.length)
+ " expected=" + payload.length);
return;
}
}
});
}
for (Thread t : threads) t.start();
for (Thread t : threads) {
t.join(30_000);
assertFalse(t.isAlive(), "thread did not finish within the join timeout");
}
assertNull(firstTear.get(), firstTear.get());
// Guard against a vacuous pass: the readers must actually have run.
assertEquals(true, reads.get() > 0, "reader threads never observed the object");
}
/** Tiny holder so the reader loop can see writers finishing without a shared executor. */
private static final class volatileDone {
final AtomicInteger count = new AtomicInteger();
}
}
@@ -0,0 +1,152 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The account-level Block Public Access operations are keyed by the {@code x-amz-account-id}
* header. Block Public Access is a security control, so the header must not be usable to read,
* overwrite or delete another account's configuration: AWS s3control requires the header to
* name the caller's own account and answers {@code AccessDenied} otherwise.
*
* <p>Every controller here shares one {@link S3Service}, as the CDI beans do — only the resolved
* caller account differs between them.
*/
class S3ControlAccountIdEnforcementTest {
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String GOVERNED_ACCOUNT = "452743914166";
private static final String OTHER_ACCOUNT = "999988887777";
private static final String CONFIG_XML =
"<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
+ "</PublicAccessBlockConfiguration>";
@TempDir
Path tempDir;
private S3Service service;
@BeforeEach
void setUp() {
service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("s3"), false);
}
@Test
void callerMayManageItsOwnAccountConfiguration() {
S3ControlController owner = controllerFor(GOVERNED_ACCOUNT);
assertEquals(200, owner.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML).getStatus());
Response read = owner.getPublicAccessBlock(GOVERNED_ACCOUNT);
assertEquals(200, read.getStatus());
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
assertEquals(204, owner.deletePublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
}
@Test
void foreignCallerCannotWriteAnotherAccountConfiguration() {
controllerFor(GOVERNED_ACCOUNT).putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
Response response = controllerFor(OTHER_ACCOUNT)
.putPublicAccessBlock(GOVERNED_ACCOUNT, "<PublicAccessBlockConfiguration/>");
assertEquals(403, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Code>AccessDenied</Code>"));
// The victim's configuration is untouched.
Response read = controllerFor(GOVERNED_ACCOUNT).getPublicAccessBlock(GOVERNED_ACCOUNT);
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
}
@Test
void foreignCallerCannotReadOrDeleteAnotherAccountConfiguration() {
controllerFor(GOVERNED_ACCOUNT).putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
S3ControlController attacker = controllerFor(OTHER_ACCOUNT);
Response read = attacker.getPublicAccessBlock(GOVERNED_ACCOUNT);
assertEquals(403, read.getStatus());
assertTrue(read.getEntity().toString().contains("<Code>AccessDenied</Code>"));
Response deleted = attacker.deletePublicAccessBlock(GOVERNED_ACCOUNT);
assertEquals(403, deleted.getStatus());
assertTrue(deleted.getEntity().toString().contains("<Code>AccessDenied</Code>"));
assertEquals(200, controllerFor(GOVERNED_ACCOUNT)
.getPublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
}
@Test
void managementAccountCallerMayManageAGovernedAccountConfiguration() {
// LZA's Custom::PutPublicAccessBlock Lambda runs under the management account's
// placeholder credentials while naming each governed account in the header.
S3ControlController management = controllerFor(DEFAULT_ACCOUNT);
assertEquals(200, management.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML).getStatus());
assertEquals(200, management.getPublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
// The config landed in the governed account's partition, not the management account's.
assertEquals(404, management.getPublicAccessBlock(DEFAULT_ACCOUNT).getStatus());
}
@Test
void missingAccountIdStillFailsAsInvalidRequest() {
Response response = controllerFor(GOVERNED_ACCOUNT).getPublicAccessBlock(" ");
assertEquals(400, response.getStatus());
assertTrue(response.getEntity().toString().contains("<Code>InvalidRequest</Code>"));
}
/**
* {@code PublicAccessBlockConfiguration} is a required member of {@code PutPublicAccessBlockRequest}.
* Block Public Access is a security control, so an empty, unparseable, or wrong-root body must
* be rejected as {@code MalformedXML} rather than silently normalized into a configuration with
* every flag defaulted to false — which would look like the caller deliberately disabled every
* protection.
*/
@Test
void putRejectsAMalformedOrWrongRootBody() {
S3ControlController owner = controllerFor(GOVERNED_ACCOUNT);
owner.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
for (String body : new String[] {null, "", "not xml",
"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>"}) {
Response response = owner.putPublicAccessBlock(GOVERNED_ACCOUNT, body);
assertEquals(400, response.getStatus(), "expected rejection for body: " + body);
assertTrue(response.getEntity().toString().contains("<Code>MalformedXML</Code>"),
"expected MalformedXML for body: " + body);
}
// The existing configuration must survive a rejected write.
Response read = owner.getPublicAccessBlock(GOVERNED_ACCOUNT);
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
}
private S3ControlController controllerFor(String callerAccountId) {
RequestContext context = new RequestContext();
context.setAccountId(callerAccountId);
@SuppressWarnings("unchecked")
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(context);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
return new S3ControlController(service, contextInstance, config);
}
}
@@ -0,0 +1,207 @@
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.Test;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* S3 bucket names are globally unique in AWS: a bucket lives in one account but is legitimately
* reachable cross-account (subject to policy). The Landing Zone Accelerator relies on this — every
* member account publishes CDK assets to one shared {@code cdk-accel-assets-<mgmt>-<region>} bucket
* owned by the management account. floci's default per-account bucket isolation breaks that path.
*
* <p>With {@code globalBucketNamespace} enabled, bucket/object <em>resolution</em> spans accounts
* while <em>listing</em> stays owner-scoped. Default-off preserves the existing isolation model
* (guarded by {@code PreSignedUrlAccountResolutionIntegrationTest}).
*/
class S3GlobalBucketNamespaceTest {
private static final String DEFAULT_ACCT = "000000000000";
private static final String ACCOUNT_A = "000000000001";
private static final String ACCOUNT_B = "000000000002";
private final AtomicReference<String> caller = new AtomicReference<>(DEFAULT_ACCT);
@SuppressWarnings("unchecked")
private Instance<RequestContext> mutableContext() {
RequestContext rc = mock(RequestContext.class);
when(rc.getAccountId()).thenAnswer(inv -> caller.get());
Instance<RequestContext> inst = mock(Instance.class);
when(inst.get()).thenReturn(rc);
return inst;
}
@Test
void bucketOwnedByOneAccountIsResolvableCrossAccountButNotListed() {
Instance<RequestContext> ctx = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-test"), true, true);
S3Service isolatedNs = new S3Service(buckets, objects, Path.of("s3-gns-test"), true, false);
// Account A owns the shared bucket and publishes a template into it.
caller.set(ACCOUNT_A);
globalNs.createBucket("shared-assets-bucket", "us-west-2");
byte[] template = "{\"Resources\":{}}".getBytes(UTF_8);
globalNs.putObject("shared-assets-bucket", "template.json", template, "application/json", Map.of());
// Account B is a different account (a member account in LZA terms).
caller.set(ACCOUNT_B);
// (1) HeadBucket resolves cross-account.
assertDoesNotThrow(() -> globalNs.headBucket("shared-assets-bucket"));
// (1) GetBucketLocation returns the owner's region cross-account.
assertEquals("us-west-2", globalNs.getBucketRegion("shared-assets-bucket"));
// (2) GetObject reads the owner's object cross-account.
assertArrayEquals(template,
globalNs.getObject("shared-assets-bucket", "template.json").getData());
// (2b) The LZA central-assets path: a member account publishes its own asset into the
// management-owned bucket (existence check must resolve cross-account), then reads it back.
byte[] memberAsset = "member-payload".getBytes(UTF_8);
assertDoesNotThrow(() ->
globalNs.putObject("shared-assets-bucket", "member-asset.json", memberAsset,
"application/json", Map.of()));
assertArrayEquals(memberAsset,
globalNs.getObject("shared-assets-bucket", "member-asset.json").getData());
// (3) Listing stays owner-scoped: account B does not see account A's bucket.
assertTrue(globalNs.listBuckets().stream()
.noneMatch(b -> "shared-assets-bucket".equals(b.getName())),
"ListBuckets must remain owner-scoped even with global namespace enabled");
// (4) Default-off preserves isolation: the same cross-account HeadBucket is NoSuchBucket.
AwsException notFound = assertThrows(AwsException.class,
() -> isolatedNs.headBucket("shared-assets-bucket"));
assertEquals("NoSuchBucket", notFound.getErrorCode());
}
/**
* Cross-account bucket-config <em>mutation</em>. LZA's {@code Custom::S3PutBucketReplication}
* custom resource runs a Lambda in the source (member) account that owns the bucket, but that
* Lambda calls back into floci under the default/management account context. The mutation must
* resolve the bucket cross-account (not 404) AND persist back to the <em>owner's</em> partition —
* a naive resolve-then-{@code put} would fork a phantom bucket into the caller's partition and
* silently lose the config on the real bucket.
*/
@Test
void putBucketReplicationResolvesAndWritesBackToOwnerCrossAccount() {
Instance<RequestContext> ctx = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-repl-test"), true, true);
// The source (member) account owns the ELB access-logs bucket.
caller.set(ACCOUNT_A);
globalNs.createBucket("elb-access-logs-bucket", "us-east-1");
// The replication custom-resource Lambda calls back under the default/management context.
caller.set(DEFAULT_ACCT);
String xml = "<ReplicationConfiguration>"
+ "<Role>arn:aws:iam::000000000001:role/replication</Role>"
+ "<Rule><Status>Enabled</Status>"
+ "<Destination><Bucket>arn:aws:s3:::central-logs</Bucket></Destination></Rule>"
+ "</ReplicationConfiguration>";
assertDoesNotThrow(() -> globalNs.putBucketReplication("elb-access-logs-bucket", xml));
// Persisted on the OWNER's bucket (account A), not the caller's partition.
Bucket owned = buckets.getForAccount(ACCOUNT_A, "elb-access-logs-bucket")
.orElseThrow(() -> new AssertionError("bucket vanished from owner partition"));
assertEquals(xml, owned.getReplicationConfiguration());
// No phantom bucket forked into the caller's default partition.
assertTrue(buckets.getForAccount(DEFAULT_ACCT, "elb-access-logs-bucket").isEmpty(),
"cross-account replication write must not fork a bucket into the caller's account");
}
/**
* The write side of {@code Custom::S3PutBucketReplication} resolves and persists cross-account
* (see {@link #putBucketReplicationResolvesAndWritesBackToOwnerCrossAccount}); the read side
* must resolve just as far, or the custom resource's own follow-up
* {@code GetBucketReplication} — and any other management-account reader — sees
* {@code NoSuchBucket} on a bucket that plainly exists in its owning account.
*/
@Test
void getBucketReplicationResolvesCrossAccount() {
Instance<RequestContext> ctx = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-repl-read-test"), true, true);
caller.set(ACCOUNT_A);
globalNs.createBucket("elb-access-logs-bucket-2", "us-east-1");
String xml = "<ReplicationConfiguration>"
+ "<Role>arn:aws:iam::000000000001:role/replication</Role>"
+ "<Rule><Status>Enabled</Status>"
+ "<Destination><Bucket>arn:aws:s3:::central-logs</Bucket></Destination></Rule>"
+ "</ReplicationConfiguration>";
globalNs.putBucketReplication("elb-access-logs-bucket-2", xml);
caller.set(DEFAULT_ACCT);
assertEquals(xml, globalNs.getBucketReplication("elb-access-logs-bucket-2"));
}
/**
* Bucket-policy operations were left on the direct {@code bucketStore.get}/{@code put} path when
* global namespace resolution was added — unlike replication and object read/write, they never got
* wired through {@code resolveBucket}/{@code mutateBucket}. A management-account caller (as the LZA
* Logging stage's policy-application step runs) must be able to put/get/delete a policy on a bucket
* owned by a member account.
*/
@Test
void bucketPolicyResolvesAndPersistsCrossAccount() {
Instance<RequestContext> ctx = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-policy-test"), true, true);
caller.set(ACCOUNT_A);
globalNs.createBucket("central-logs-bucket", "us-east-1");
caller.set(DEFAULT_ACCT);
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
assertDoesNotThrow(() -> globalNs.putBucketPolicy("central-logs-bucket", policy));
assertEquals(policy, globalNs.getBucketPolicy("central-logs-bucket"));
// Persisted on the OWNER's bucket (account A), not forked into the caller's partition.
Bucket owned = buckets.getForAccount(ACCOUNT_A, "central-logs-bucket")
.orElseThrow(() -> new AssertionError("bucket vanished from owner partition"));
assertEquals(policy, owned.getPolicy());
assertTrue(buckets.getForAccount(DEFAULT_ACCT, "central-logs-bucket").isEmpty(),
"cross-account putBucketPolicy must not fork a bucket into the caller's account");
assertDoesNotThrow(() -> globalNs.deleteBucketPolicy("central-logs-bucket"));
AwsException notFound = assertThrows(AwsException.class,
() -> globalNs.getBucketPolicy("central-logs-bucket"));
assertEquals("NoSuchBucketPolicy", notFound.getErrorCode());
}
}
@@ -172,8 +172,109 @@ class S3ReplicationConfigurationIntegrationTest {
.body(containsString("<ID>rule2</ID>"));
}
/**
* {@code ReplicationRule/Status} is Required: Yes with enum {@code Enabled|Disabled}.
* Storing a rule with any other status — or with none — makes the emulator answer a
* later GetBucketReplication with a document AWS would never have accepted.
*/
@Test
@Order(8)
void putReplicationRejectsARuleStatusOutsideTheEnum() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>bad-status</ID>
<Status>enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
</Destination>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(200)
.body(not(containsString("bad-status")));
}
@Test
@Order(9)
void putReplicationRejectsARuleWithNoStatus() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>no-status</ID>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
</Destination>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(200)
.body(not(containsString("no-status")));
}
/**
* Each {@code Rule} requires its own {@code Destination/Bucket}; a document-wide check that
* only looks for one {@code Bucket} anywhere in the XML is satisfied when just one of several
* rules has a destination, so a rule missing one round-trips as a configuration AWS would
* have rejected as {@code MalformedXML}.
*/
@Test
@Order(10)
void putReplicationRejectsARuleWithoutItsOwnDestinationBucket() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>has-destination</ID>
<Status>Enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
</Destination>
</Rule>
<Rule>
<ID>missing-destination</ID>
<Status>Enabled</Status>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(200)
.body(not(containsString("missing-destination")));
}
@Test
@Order(11)
void putReplicationOnMissingBucketReturns404() {
given()
.body(REPLICATION_XML)
@@ -185,7 +286,7 @@ class S3ReplicationConfigurationIntegrationTest {
}
@Test
@Order(9)
@Order(12)
void getReplicationOnMissingBucketReturns404() {
given()
.when()
@@ -202,7 +303,7 @@ class S3ReplicationConfigurationIntegrationTest {
* /{bucket}?replication} would have fallen through to {@code DeleteBucket}.
*/
@Test
@Order(10)
@Order(13)
void deleteReplicationClearsTheStoredConfiguration() {
given()
.when()
@@ -224,7 +325,7 @@ class S3ReplicationConfigurationIntegrationTest {
/** Matching real S3, deleting an already-absent configuration still answers 204. */
@Test
@Order(11)
@Order(14)
void deleteReplicationWithoutConfigurationStillReturns204() {
given()
.when()
@@ -234,7 +335,7 @@ class S3ReplicationConfigurationIntegrationTest {
}
@Test
@Order(12)
@Order(15)
void deleteReplicationOnMissingBucketReturns404() {
given()
.when()
@@ -252,7 +353,7 @@ class S3ReplicationConfigurationIntegrationTest {
* the two.
*/
@Test
@Order(13)
@Order(16)
void accelerateAndReplicationPrecedenceFollowsEachMethodsDispatchOrder() {
String bucket = "replication-precedence-test";
given()
@@ -315,4 +416,86 @@ class S3ReplicationConfigurationIntegrationTest {
.statusCode(404)
.body(containsString("ReplicationConfigurationNotFoundError"));
}
/**
* A document-wide count of Rule elements against Destination elements can't distinguish a
* well-formed document from one where a rule improperly carries two Destinations and another
* rule carries none — the totals still balance (2 rules, 2 destinations) even though the
* second rule has no destination of its own and the first has one too many.
*/
@Test
@Order(17)
void putReplicationRejectsWhenDestinationsAreNotOnePerRule() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>two-destinations</ID>
<Status>Enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
</Destination>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target-2</Bucket>
</Destination>
</Rule>
<Rule>
<ID>zero-destinations</ID>
<Status>Enabled</Status>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
// BUCKET has no configuration at this point in the ordered sequence (cleared by
// deleteReplicationClearsTheStoredConfiguration, @Order(13)), so the rejected PUT above
// must not have stored anything either.
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(404)
.body(containsString("ReplicationConfigurationNotFoundError"));
}
/**
* {@code Destination.Bucket} is a required <em>scalar</em> member (botocore
* s3/2006-03-01/service-2.json: {@code "Bucket":{"shape":"BucketName"}}, not a list) — a
* Destination with two Bucket children is not a valid alternative encoding, it is malformed.
* Selecting only the first Bucket child would silently accept the second as if it never
* existed and store a document AWS would reject.
*/
@Test
@Order(18)
void putReplicationRejectsADestinationWithMultipleBucketElements() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>two-buckets</ID>
<Status>Enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
<Bucket>arn:aws:s3:::replication-config-int-test-target-2</Bucket>
</Destination>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(404)
.body(containsString("ReplicationConfigurationNotFoundError"));
}
}
@@ -8,12 +8,26 @@ import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3ReplicationIntegrationTest {
private static final String BUCKET = "replication-int-test";
private static final String WEST_BUCKET = "replication-int-test-west";
private static final String REPLICATION_XML = """
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
<Rule>
<ID>rule-1</ID>
<Status>Enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-dest</Bucket>
</Destination>
</Rule>
</ReplicationConfiguration>
""";
@Test
@Order(1)
@@ -25,6 +39,17 @@ class S3ReplicationIntegrationTest {
.statusCode(200);
}
@Test
@Order(2)
void getReplicationBeforePutReturns404() {
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(404)
.body(containsString("ReplicationConfigurationNotFoundError"));
}
/**
* Regression test for the bucket-destroying bug where {@code DELETE /{bucket}?replication}
* (DeleteBucketReplication) was not handled and fell through to the unqualified
@@ -32,7 +57,7 @@ class S3ReplicationIntegrationTest {
* replication configuration and returns 204.
*/
@Test
@Order(2)
@Order(3)
void deleteReplicationDoesNotDeleteBucket() {
given()
.when()
@@ -42,7 +67,7 @@ class S3ReplicationIntegrationTest {
}
@Test
@Order(3)
@Order(4)
void bucketStillExistsAfterReplicationDelete() {
// A sub-resource-qualified DELETE must never remove the bucket itself.
given()
@@ -53,7 +78,7 @@ class S3ReplicationIntegrationTest {
}
@Test
@Order(4)
@Order(5)
void putVersioningAfterReplicationDeleteSucceeds() {
given()
.body("""
@@ -68,7 +93,111 @@ class S3ReplicationIntegrationTest {
}
@Test
@Order(5)
@Order(6)
void putReplicationStoresConfiguration() {
given()
.body(REPLICATION_XML)
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(200);
}
@Test
@Order(7)
void getReplicationRoundTripsStoredConfiguration() {
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(200)
.body(containsString("<Role>arn:aws:iam::000000000000:role/replication-role</Role>"))
.body(containsString("<ID>rule-1</ID>"))
.body(containsString("<Status>Enabled</Status>"))
.body(containsString("<Bucket>arn:aws:s3:::replication-dest</Bucket>"));
}
@Test
@Order(8)
void putReplicationWithoutRoleReturnsMalformedXml() {
given()
.body("""
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Rule>
<Status>Enabled</Status>
<Destination>
<Bucket>arn:aws:s3:::replication-dest</Bucket>
</Destination>
</Rule>
</ReplicationConfiguration>
""")
.when()
.put("/" + BUCKET + "?replication")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
}
@Test
@Order(9)
void deleteReplicationRemovesConfiguration() {
given()
.when()
.delete("/" + BUCKET + "?replication")
.then()
.statusCode(204);
given()
.when()
.get("/" + BUCKET + "?replication")
.then()
.statusCode(404)
.body(containsString("ReplicationConfigurationNotFoundError"));
}
/**
* Regression test for {@code PUT /{bucket}?replication} falling through to CreateBucket:
* outside us-east-1 the fall-through surfaced as {@code 409 BucketAlreadyOwnedByYou}
* (and in us-east-1 as a silent false success).
*/
@Test
@Order(10)
void putReplicationOnNonUsEast1BucketDoesNot409() {
given()
.body("""
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<LocationConstraint>us-west-2</LocationConstraint>
</CreateBucketConfiguration>
""")
.when()
.put("/" + WEST_BUCKET)
.then()
.statusCode(200);
given()
.body(REPLICATION_XML)
.when()
.put("/" + WEST_BUCKET + "?replication")
.then()
.statusCode(200)
.body(not(containsString("BucketAlreadyOwnedByYou")));
given()
.when()
.get("/" + WEST_BUCKET + "?replication")
.then()
.statusCode(200)
.body(containsString("<ID>rule-1</ID>"));
given()
.when()
.delete("/" + WEST_BUCKET)
.then()
.statusCode(204);
}
@Test
@Order(11)
void unqualifiedDeleteStillRemovesBucket() {
given()
.when()
+1
View File
@@ -122,6 +122,7 @@ floci:
enabled: true
enforce-auth: false
default-presign-expiry-seconds: 3600
global-bucket-namespace: false
dynamodb:
enabled: true
sns: