mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
f1ad306599
commit
c96dc98065
17 files changed
+1515
-77
No files matched your search
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user